我正在使用Multipeer Connectivity框架。我正在NSUserDefaults中保存我的PeerId以重复使用它(如Apple建议的那样)(下面的代码是swift但是Objective c也有相同的行为)。 :
var peerId: MCPeerID = {
let defaults = NSUserDefaults.standardUserDefaults();
let dataToShow = defaults.dataForKey("kPeerID");
var peer = NSKeyedUnarchiver.unarchiveObjectWithData(dataToShow) as? MCPeerID;
if peer == nil {
peer = MCPeerID(displayName: UIDevice.currentDevice().name);
let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(peer);
defaults.setObject(data, forKey: "kPeerID");
defaults.synchronize();
}
println("I am peer: \(peer!)");
return peer!;
}()
我将邀请发送给发现的同行:
func browser(browser: MCNearbyServiceBrowser!, foundPeer peerID: MCPeerID!, withDiscoveryInfo info: [NSObject : AnyObject]!) {
println("\(self.peerId) Found peer \(peerID)");
if let browserSession = self.session {
browserSession.delegate = self;
browser.invitePeer(peerID, toSession: browserSession, withContext: nil, timeout: 30);
}else {
println("Browser session is nil");
}
}
广告商使用代码找到它:
func advertiser(advertiser: MCNearbyServiceAdvertiser!, didReceiveInvitationFromPeer peerID: MCPeerID!, withContext context: NSData!, invitationHandler: ((Bool, MCSession!) -> Void)!) {
println("\(self.peerId) Received Invitation from \(peerID)");
var session = availableSession();
invitationHandler(true, session);
}
我面临的问题是:当广告客户找到peerId时,它会显示与原始peerId不同的peerId,但显示名称正确。
浏览器控制台输出是:
I am peer: <MCPeerID: 0x1663e670 DisplayName = Jon Yang’s iPad>
<MCPeerID: 0x1663e670 DisplayName = Jon Yang’s iPad> Received Invitation from <MCPeerID: 0x1666daf0 DisplayName = Jon Yang’s iPadMini>
<MCPeerID: 0x1663e670 DisplayName = Jon Yang’s iPad> Connecting with <MCPeerID: 0x1666daf0 DisplayName = Jon Yang’s iPadMini>
<MCPeerID: 0x1663e670 DisplayName = Jon Yang’s iPad> Connected with <MCPeerID: 0x1666daf0 DisplayName = Jon Yang’s iPadMini>
和广告商控制台输出为:
I am peer: <MCPeerID: 0x1569d230 DisplayName = Jon Yang’s iPadMini>
<MCPeerID: 0x1569d230 DisplayName = Jon Yang’s iPadMini> Found peer <MCPeerID: 0x15586600 DisplayName = Jon Yang’s iPad>
<MCPeerID: 0x1569d230 DisplayName = Jon Yang’s iPadMini> Connecting with <MCPeerID: 0x15586600 DisplayName = Jon Yang’s iPad>
<MCPeerID: 0x1569d230 DisplayName = Jon Yang’s iPadMini> Connected with <MCPeerID: 0x15586600 DisplayName = Jon Yang’s iPad>
正如您所看到的,即使Browser和Advertiser有他们的peerId信息,当他们被其他同伴收到时,他们的peerId也是不同的。有谁能解释一下?有什么我做错了吗?
答案 0 :(得分:2)
<MCPeerID: 0x1663e670 DisplayName = Jon Yang’s iPad>
0x1663e670
表示当前设备上MCPeerID
对象的内存地址。不要将它与框架引用的实际MCPeerID
对象混淆。只要displayName
符合预期,那么它就是正确的同行。