正如@kdogisthebest 正确指出的那样,没有办法强制 Multipeer Connectivity 使用特定的网络技术,但是由于您的问题与 WiFi 的特定问题有关,这个答案详细说明了我正在做的工作来解决这个问题.
在创建MCNearybyServiceAdvertiser 时,我通过在discoveryInfo 中发送缩短的时间戳来解决WiFi 上的“幻像”对等点的问题。这里有几个警告:
1) 此解决方案假定两个设备具有相同的时间。我通过使用 ios-ntp 的修改版本作为应用的时间源来确保这一点。
2) 它还假设广告和浏览不会运行太久。我为发现阶段设置了 60 秒的长度,并且每次重新启动时我都会完全重新启动浏览器/广告商。
3) MPC 似乎不喜欢 discoveryInfo 中的太多字节,因此基于 epoch 发送 NSTimeInterval 不起作用。我不得不截断它们。
所以当我的应用进入发现模式时,它会同时开始浏览和投放广告。广告代码如下:
- (void)startAdvertising {
if (_advertising){
NSLog(@"Already advertising");
return;
}
self.acceptedPeerIDNameMap = [NSMutableDictionary dictionary];
NSInteger timeStamp = [self shortenedNetworkTimeStamp];
NSDictionary *discoveryInfo = @{kAdvertisingDiscoveryInfoTimestampKey:[NSString stringWithFormat:@"%ld",(long)timeStamp]};
NSLog(@"Starting advertiser");
self.serviceAdvertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:_myPeerID
discoveryInfo:discoveryInfo
serviceType:kServiceType];
_serviceAdvertiser.delegate = self;
[_serviceAdvertiser startAdvertisingPeer];
self.advertising = YES;
}
shortenedNetworkTimestamp 方法只需要一个 NSTimeInterval(使用 ntp 框架或 timeIntervalSinceReferenceDate 并从中删除 1400000000。
然后,当浏览器发现对等点时,它会检查广告商的时间戳是否在已知的发现持续时间(在我的情况下为 60 秒)内:
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info {
DLog(@"Browser found peer ID %@",peerID.displayName);
//Only one peer should invite the other
BOOL shouldInvite = [peerID.displayName compare:_myPeerID.displayName]==NSOrderedAscending;
//Don't re-send invitations
if (_peerInfoDisplayNameMap[peerID.displayName]){
DLog(@"Already connected to peerID %@",peerID.displayName);
shouldInvite = NO;
}
else if (_invitedPeerIDNameMap[peerID.displayName]){
DLog(@"Already invited peerID %@",peerID.displayName);
shouldInvite = NO;
}
//Invite if discovery info is valid
if (shouldInvite && [self discoveryInfoIsValid:info]) {
DLog(@"Inviting");
_invitedPeerIDNameMap[peerID.displayName] = peerID;
MCSession *session = [self availableSession];
[_serviceBrowser invitePeer:peerID toSession:session withContext:nil timeout:0];
}
else {
DLog(@"Not inviting");
}
}
发现信息有效性检查非常简单 - 只需确保信息中发送的时间戳在发现时间范围内(在我的情况下 kDiscoveryPhaseDuration 是 60 秒):
- (BOOL)discoveryInfoIsValid:(NSDictionary *)info {
BOOL isValid = YES;
NSString *infoTimeStamp = info[kAdvertisingDiscoveryInfoTimestampKey];
NSTimeInterval sentTimeStamp = (infoTimeStamp) ? [infoTimeStamp doubleValue] : -1;
NSTimeInterval currentTimeStamp = [self shortenedNetworkTimeStamp];
if (sentTimeStamp==-1 || (currentTimeStamp - sentTimeStamp) > kDiscoveryPhaseDuration){
DLog(@"Expired discovery info (current=%f, sent=%f)",currentTimeStamp,sentTimeStamp);
isValid = NO;
}
return isValid;
}
希望这会有所帮助。我在自己的代码中处理 MPC 中的许多其他怪癖,但我认为以上内容涵盖了这个特定问题。