简体   繁体   中英

Issue with Multipeer Connectivity Framework in iOS

I'm experimenting with Multipeer Connectivity Framework in iOS. I want to make a simple app that advertises the device and also browses for other devices. Here is my code:

class ViewController: UIViewController {

    static let serviceType = "mult-demo"
    let localPeerID = MCPeerID(displayName: UIDevice.currentDevice().name)

    func startAdvertising() {
        let advertiser = MCNearbyServiceAdvertiser(peer: localPeerID, discoveryInfo: nil, serviceType: ViewController.serviceType)
    advertiser.delegate = self
    advertiser.startAdvertisingPeer()
    print("advertising")
    }

    func startBrowsing() {
        let browser = MCNearbyServiceBrowser(peer: localPeerID, serviceType: ViewController.serviceType)
        browser.delegate = self
        browser.startBrowsingForPeers()
        print("browsing")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        startAdvertising()
        startBrowsing()
    }

}

extension ViewController : MCNearbyServiceAdvertiserDelegate, MCNearbyServiceBrowserDelegate {
    func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: (Bool, MCSession) -> Void) {

        print("received invitation")
    }

    func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
        print("found peer \(peerID)")
    }

    func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {

    }
}

However, when I run it on two iPads (iOS 9) connected to the same wifi network they don't discover each other. What am I doing wrong?

As mentioned in the comments, for first you need to make sure the "instance" of the browser and advertiser are not lost by keeping a strong reference to them. You can do that by declaring an instance variable. As apposed to a local variable.

Also, you need to make sure that either the devices are on the same wifi network OR have both bluetooth and wifi on.

Multipeer Connectivity works between iOS only and i believe has a rater complicated api..

After the discovery you will still need to handle quite a lot of logics with regards to content exchange. Also if you would ever want your app to work with Android this wont be possible.

If i may, i would recommend going for SDKs that can do peer-to-peer communication for you as those would save ALOT of development and maintenance time.

For example try: http://www.p2pkit.io , http://www.intromi.co and http://www.underdark.io or google nearby

I hope this helps...

Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM