iOS12 Swift 5.x
我正在使用Multipeer Connectivity。到目前为止,如果我以正确的顺序连接设备,效果很好。
使用样板代码,将问题跟踪到这里。
func setupStream() {
do {
outputStream = try session.startStream(withName: "chat", toPeer: session.connectedPeers.first!)
for debug in session.connectedPeers {
print("Peer connected \(debug.displayName)")
}
} catch {
print("unable to open stream")
}
if let outputStream = outputStream {
outputStream.delegate = self
outputStream.schedule(in: RunLoop.main, forMode:RunLoop.Mode.default)
outputStream.open()
}
}
现在,如果我先启动广告商,然后再启动浏览器,那么它会很好地运行。但是,如果我在广告商之前启动浏览器,它们似乎会彼此见面……即使我不是从它们来做广告,也不是从它们来做服务并连接到错误的客户端。
怎么说与广告服务的同行建立联系,而不是任何人和您找到的每个人...
答案 0 :(得分:0)
iOS 12,Swift 5
找到了一个我在这里发布的解决方案,一个很好的简单解决方案。广告服务时,我会提供一些发现信息。这里的关键是发现变量。
块看起来这样。
class ColorService : NSObject {
lazy var session : MCSession = {
let session = MCSession(peer: self.myPeerId, securityIdentity: nil, encryptionPreference: .required)
session.delegate = self
return session
}()
var delegate : ColorServiceDelegate?
// Service type must be a unique string, at most 15 characters long
// and can contain only ASCII lowercase letters, numbers and hyphens.
private let ColorServiceType = "example-color"
private let myPeerId = MCPeerID(displayName: UIDevice.current.name)
private let serviceAdvertiser : MCNearbyServiceAdvertiser
override init() {
let discover:[String:String] = ["prime":myPeerId.displayName]
self.serviceAdvertiser = MCNearbyServiceAdvertiser(peer: myPeerId, discoveryInfo: discover, serviceType: ColorServiceType)
super.init()
self.serviceAdvertiser.delegate = self
self.serviceAdvertiser.startAdvertisingPeer()
}
deinit {
self.serviceAdvertiser.stopAdvertisingPeer()
}
func stopAdvertising() {
self.serviceAdvertiser.stopAdvertisingPeer()
}
另一方面,当我在寻找服务时,我仅邀请具有发现设置的对等方,显然是使用上述信息作为邀请方。
extension ColorSearch : MCNearbyServiceBrowserDelegate {
func browser(_ browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: Error) {
NSLog("%@", "didNotStartBrowsingForPeers: \(error)")
}
func browser(_ browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?) {
NSLog("%@", "foundPeer: \(peerID)")
NSLog("%@", "invitePeer: \(peerID)")
NSLog("%@", "discoverInfo: \(info)")
primePeer = info!["prime"]
if primePeer != nil {
if peerID.displayName == primePeer {
browser.invitePeer(peerID, to: self.session, withContext: nil, timeout: 10)
}
}
}
func browser(_ browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID) {
NSLog("%@", "lostPeer: \(peerID)")
}
func disconnect() {
self.session.disconnect()
}
我没有连接矩阵,只有一个主机和一堆从机。也许不是打算实现多对等连接,但是一个好的解决方案则永远如此。