我在列表中看不到广告客户。我在设备和模拟器上运行此代码,你知道为什么吗?
以下是添加到主viewcontroller的所有代码。我正在使用nshipser multipeer connectivity教程:
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
static NSString * const XXServiceType = @"xx-service";
localPeerID = [[MCPeerID alloc] initWithDisplayName:[[UIDevice currentDevice] name]];
MCNearbyServiceAdvertiser *advertiser =
[[MCNearbyServiceAdvertiser alloc] initWithPeer:localPeerID
discoveryInfo:nil
serviceType:XXServiceType];
advertiser.delegate = self;
[advertiser startAdvertisingPeer];
MCSession *session = [[MCSession alloc] initWithPeer:localPeerID
securityIdentity:nil
encryptionPreference:MCEncryptionNone];
session.delegate = self;
MCNearbyServiceBrowser *browser = [[MCNearbyServiceBrowser alloc] initWithPeer:localPeerID serviceType:XXServiceType];
browser.delegate = self;
MCBrowserViewController *browserViewController =
[[MCBrowserViewController alloc] initWithBrowser:browser
session:session];
browserViewController.view.backgroundColor = [UIColor redColor];
browserViewController.delegate = self;
self.modalPresentationStyle = UIModalPresentationFullScreen;
[self presentViewController:browserViewController animated:YES completion:
^{
[browser startBrowsingForPeers];
}];
}
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void(^)(BOOL accept, MCSession *session))invitationHandler
{
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"didReceiveInvitationFromPeer get called" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
[av show];
if ([self.mutableBlockedPeers containsObject:peerID]) {
invitationHandler(NO, nil);
return;
}
[self.mutableBlockedPeers addObject:peerID];
MCSession *session = [[MCSession alloc] initWithPeer:localPeerID
securityIdentity:nil
encryptionPreference:MCEncryptionNone];
session.delegate = self;
invitationHandler(YES, session);
}
答案 0 :(得分:5)
您的代码存在两个主要问题。
首先,您没有对广告客户有任何强烈的引用,因此一旦viewDidAppear完成,它将被解除分配(从而广告停止)。
因此,请确保向视图控制器添加属性并将广告商存储在其中:
@interface ViewController()<MCNearbyServiceAdvertiserDelegate, etc>
@property(nonatomic, strong) MCNearbyServiceAdvertiser *advertiser;
@end
...
- (void)viewDidAppear:(BOOL)animated {
... create the advertiser, etc
self.advertiser = advertiser
... etc
}
第二个问题源于您创建和使用浏览器对象。
来自Apple的MCBrowserViewController
课程文档:
重要提示:如果您希望浏览器视图控制器管理浏览过程,则浏览器对象不得主动浏览,其委托必须为零。
因此,删除显示browser.delegate = self
的行,并删除包含[browser startBrowsingForPeers]
的代码块(代之以传递nil),因为浏览器视图控制器会为您执行此操作。< / p>
或者,甚至不要直接创建浏览器对象,而是让浏览器视图控制器使用其他init方法代替它:
MCBrowserViewController *browserViewController = [[MCBrowserViewController alloc] initWithServiceType:XXServiceType session:session];