MultipeerConnectivity declining connection

102 Views Asked by At

I'm trying to set up a bluetooth connection between two devices, here's my code:

var peerID: MCPeerID!
var mcSession: MCSession!
var mcAdvertiserAssistant: MCAdvertiserAssistant!

@IBAction func connectBlueTooth(_ sender: Any) {
    let actionSheet = UIAlertController(title: "משחק רשת", message: "מעוניין ליצור משחק חדש או להצטרף למשחק קיים?", preferredStyle: .actionSheet)

    actionSheet.addAction(UIAlertAction(title: "יצירת משחק חדש", style: .default, handler: {
        (action: UIAlertAction) in
        self.startHosting()
    }))

    actionSheet.addAction(UIAlertAction(title: "חיפוש משחק קיים", style: .default, handler: {
        (action: UIAlertAction) in
        self.joinSession()
    }))

    actionSheet.addAction(UIAlertAction(title: "ביטול", style: .default, handler: nil))

    if let popoverController = actionSheet.popoverPresentationController {
        popoverController.sourceView = self.view
        let constraintValue = AppConfigurator.getConstraintByDevice()

        popoverController.sourceRect = CGRect(x: self.view.bounds.maxX - constraintValue, y: self.view.bounds.maxY - (3.5 * constraintValue), width: 0, height: 0)
        popoverController.permittedArrowDirections = []
    }

    self.present(actionSheet, animated: true, completion: nil)
}

And the extensions:

extension MainMenuVC: MCBrowserViewControllerDelegate {
    func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
        dismiss(animated: true, completion: nil)
    }

    func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
        dismiss(animated: true, completion: nil)
    }
}

extension MainMenuVC: MCSessionDelegate {
        func startHosting() {
            mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "CatchTheDragon", discoveryInfo: nil, session: mcSession)
            mcAdvertiserAssistant.start()
        }

        func joinSession() {
            let mcBrowser = MCBrowserViewController(serviceType: "CatchTheDragon", session: mcSession)
            mcBrowser.delegate = self
            present(mcBrowser, animated: true)
        }

        func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
            switch state {
            case MCSessionState.connected:
                print("Connected: \(peerID.displayName)")

            case MCSessionState.connecting:
                print("Connecting: \(peerID.displayName)")

            case MCSessionState.notConnected:
                print("Not Connected: \(peerID.displayName)")
            }
        }

        func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
            let userInfo = ["data" : data, "peerID": peerID] as [String : Any]
            DispatchQueue.main.async {
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "WPC_DidReceiveDataNotification"), object: nil, userInfo: userInfo)
            }
        }

        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?) {}   
}

For some reason the device gets stuck in "connecting" state eventually resolved in "declined" state. I prefer not using MCNearbyServiceAdvertiserDelegate and MCNearbyServiceBrowser. What am I missing here?

1

There are 1 best solutions below

0
On

I had the same issue but I found the following article with a fix: "Multipeer Сonnectivity Framework in Swift: tutorial"

Can’t get alert to join a session from another device?

Well, that is a common problem that appeared in XCode 11.2 and iOS 13 and still exists. We don’t know if Apple find the framework obsolete or will fix it later. One of the solutions can be — downgrade from using SceneDelegate and AppDelegate to only one class: AppDelegate and leave using UIScene for future apps, not this one.

  • first, completely remove the “Application Scene Manifest” entry from Info.plist;
  • remove the SceneDelegate class, and remove all scene related methods in your AppDelegate;
  • if missing, add the property var window: UIWindow? to your AppDelegate class.

Your app should now only use the app delegate and under iOS 13 it will have the same life cycle as iOS 12. And Multipeer connectivity should work as it is originally designed.