PyObjC Framework: MultipeerConnectivity

12.1 · active · verified Tue Apr 14

The `pyobjc-framework-multipeerconnectivity` library provides Python bindings for Apple's Multipeer Connectivity framework on macOS, enabling Python applications to discover nearby devices and communicate via Wi-Fi, Peer-to-Peer Wi-Fi, and Bluetooth personal area networks. It is part of the larger PyObjC project, allowing Python developers to interact with Objective-C APIs directly. The current version is 12.1, and releases generally align with macOS SDK updates and Python version compatibility.

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up `MCNearbyServiceBrowser` and `MCNearbyServiceAdvertiser` to discover and be discovered by other devices using Multipeer Connectivity. It defines Python classes to act as delegates for handling discovery events and runs a console event loop to process callbacks. This simplified example focuses on peer discovery rather than full session management or data transfer.

import objc
from Foundation import *
from MultipeerConnectivity import *
from PyObjCTools import AppHelper
import sys

# Define a service type (must be 1-15 lowercase ASCII characters, no hyphens, no underscores)
SERVICE_TYPE = "my-p2p-app"

class BrowserDelegate(NSObject):
    """
    Delegate for MCNearbyServiceBrowser to handle found and lost peers.
    """
    def browser_foundPeer_withDiscoveryInfo_(self, browser, peerID, info):
        print(f"[Browser] Found peer: {peerID.displayName()} (Info: {info})")
        # In a real app, you'd now invite the peer to a session.

    def browser_lostPeer_(self, browser, peerID):
        print(f"[Browser] Lost peer: {peerID.displayName()}")

class AdvertiserDelegate(NSObject):
    """
    Delegate for MCNearbyServiceAdvertiser to handle invitations.
    """
    def advertiser_didReceiveInvitationFromPeer_withContext_invitationHandler_(self, advertiser, peerID, context, invitationHandler):
        print(f"[Advertiser] Received invitation from {peerID.displayName()} (Context: {context})")
        # For this simple example, we decline any invitations.
        invitationHandler(False, None) 

# 1. Create a peer ID for this device
myPeerID = MCPeerID.alloc().initWithDisplayName_(NSHost.currentHost().name())
print(f"Starting MultipeerConnectivity as: {myPeerID.displayName()}")

# 2. Setup a browser to find other peers
browserDelegate = BrowserDelegate.alloc().init()
browser = MCNearbyServiceBrowser.alloc().initWithPeer_serviceType_(myPeerID, SERVICE_TYPE)
browser.setDelegate_(browserDelegate)
browser.startBrowsingForPeers()
print(f"Started browsing for peers using service type: '{SERVICE_TYPE}'")

# 3. Setup an advertiser to be discovered by other peers
advertiserDelegate = AdvertiserDelegate.alloc().init()
advertiser = MCNearbyServiceAdvertiser.alloc().initWithPeer_discoveryInfo_serviceType_(myPeerID, None, SERVICE_TYPE)
advertiser.setDelegate_(advertiserDelegate)
advertiser.startAdvertisingPeer()
print(f"Started advertising using service type: '{SERVICE_TYPE}'")

print("\n--- Running event loop. Press Ctrl+C to stop. ---")
try:
    AppHelper.runConsoleEventLoop(installInterrupt=True)
except KeyboardInterrupt:
    print("\nStopping...")
finally:
    browser.stopBrowsingForPeers()
    advertiser.stopAdvertisingPeer()
    print("Stopped browsing and advertising.")
    sys.exit(0)

view raw JSON →