我正在iOS中嘗試Multipeer連接框架。我想製作一個簡單的應用程序,通知設備並瀏覽其他設備。這裏是我的代碼:iOS中Multipeer連接框架的問題
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) {
}
}
然而,當我在連接到相同的WiFi網絡,他們不會發現彼此的兩個臺iPad(iOS版9)運行它。我究竟做錯了什麼?
您應該將'browser'和'advertiser'保存在屬性而不是局部變量中,因爲它們將在功能退出時釋放 – Paulw11
@ Paulw11我修復了它但它仍然無效:(已解決 – Ruslan
@ Paulw11問題,非常感謝) – Ruslan