Disclaimer: This fix is working for me as of August 2021
So I was following the original tutorial and by the end of day 84 was still not able to get the code working 😅.
After browsing our forum, googling and StackOverflowing, I’ve figured a solution to fix the issue of it not letting you connect to the session hosting device:
- In
Info.plist
, make sure you have these 3 keys:
- "Privacy Local Network Usage Description":
"Insert your own description here...."
- "Bonjour services" in that there’re 2 child keys:
- Item 0:
_hws-project25._tcp
- Item 1:
_hws-project25._udp
(note the underscores (_) in those keys)
- In your main
ViewController
, make these edits:
// in your properties list
var mcAdAssistant: MCNearbyServiceAdvertiser?
// in your startHosting(:) code
func startHosting(via action: UIAlertAction) {
guard mcSession != nil else { return }
mcAdAssistant = MCNearbyServiceAdvertiser(peer: peerID, discoveryInfo: nil, serviceType: MCConnectivity.serviceID)
mcAdAssistant?.delegate = self
mcAdAssistant?.startAdvertisingPeer()
}
// also just in case if you decided to go a step further and have a stopSession(:) method
func stopSession(via action: UIAlertAction) {
mcAdAssistant?.stopAdvertisingPeer()
mcSession?.disconnect()
}
// MOST IMPORTANT PART TO THE FIX
// conform your VC to MCNearbyServiceAdvertiserDelegate
// then implement this method didReceiveInvitationFromPeer(:)
func advertiser(_ advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: Data?, invitationHandler: @escaping (Bool, MCSession?) -> Void) {
let ac = UIAlertController(title: title, message: "\(peerID.displayName) wants to connect", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Allow", style: .default, handler: { [weak self] _ in
invitationHandler(true, self?.mcSession)
}))
ac.addAction(UIAlertAction(title: "Decline", style: .cancel, handler: { _ in
invitationHandler(false, nil)
}))
present(ac, animated: true)
}
- In my case, there was no need to alter the code of my
mcBrowser
, AppDelegate.swift
, or Application Scene Manifest
keys of Info.plist
whatsoever (thank God 😅)
Bonus: In case you wanna check out my code, here you are 🤗. Happy coding fellas 🥳👋🏻