我想你把它弄反了。IFAIK,MCAdvertiserAssistant 的discoveryInfo 是从广告商传递给浏览器的信息。此信息传递给:
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info
这是 MCNearbyServiceBrowser 类的委托方法。对此:
– browserViewController:shouldPresentNearbyPeer:withDiscoveryInfo:
Which is the delegate for the MCBrowserViewController class.
此信息应用于检查是否应为您的用户显示此广告商。
如果您有兴趣拦截邀请尝试,则应考虑使用 MCNearbyServiceAdvertiser 类而不是助手。这样,您可以委托 didReceiveInvitationFromPeer 方法并向其添加一些自定义逻辑:
// pedido para entrar na sala.
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID
withContext:(NSData *)context
invitationHandler:(void (^)(BOOL accept, MCSession *session))invitationHandler {
// get the browser's info
NSDictionary *peerInfo = (NSDictionary *) [NSKeyedUnarchiver unarchiveObjectWithData:context];
//check if peer is valid for this room (add your custom logic in this method)
if ([self isValidForThisRoom:peerInfo]) {
//create an alert
NSObject *clientName = [peerInfo valueForKey:@"playerName"];
NSString *clientMessage = [[NSString alloc] initWithFormat:@"%@ wants to connect. Accept?", clientName];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:@"Accept Connection?"
message:clientMessage
delegate:self
cancelButtonTitle:@"No"
otherButtonTitles:@"Yes", nil];
[alertView show];
// copy the invitationHandler block to an array to use it later
ArrayInvitationHandler = [NSArray arrayWithObject:[invitationHandler copy]];
} else {
// if the peer is not valid, decline the invitation
invitationHandler(NO, _session);
}
}
在 alertview 的 clickedButtonAtIndex 委托上,您可以执行以下操作:
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
//obtem a decisao do usuario
BOOL accept = (buttonIndex != alertView.cancelButtonIndex) ? YES : NO;
// obtem o invitationHandler que foi guardado do didReceiveInvitationFromPeer
void (^invitationHandler)(BOOL, MCSession *) = [ArrayInvitationHandler objectAtIndex:0];
// chama o invitationHandler passando a nossa session
invitationHandler(accept, _session);
}
需要注意的两个重要事项是:
您的会话对象应该是一个实例变量,而不是我在一些代码示例中看到的本地变量。根据我的经验,我刚刚创建了一个静态共享实例来存储会话对象。如果您想将会话从一个屏幕传递到另一个屏幕,这也是一个不错的计划。
请注意,您应该创建一个 NSArray *ArrayInvitationHandler; 变量来存储块代码。我试图做 Block_copy 但它发生了一些转换错误,所以stackoverflow 中的某个人决定存储在一个数组中,我认为这已经足够优雅了。
无论如何,我使用这个设置让它工作了。希望它可以帮助你:D