我有一个正在使用MultiPeer Connectivity框架的应用程序。每当应用程序在AppDelegate中变为事件状态时,我都将创建一个新的MCSession,一个MCNearbyBrowserService和一个MCNearbyAdvertiserService,并调用开始浏览并开始广告。然后,每当应用程序在AppDelegate中变为非事件状态时,我都会停止浏览和转换广告,并将所有内容都设置为nil。我发现MCNearbyBrowserService导致其syncQueue崩溃:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** - [__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[2]'
*** First throw call stack:
(0x2de3ee8b 0x381396c7 0x2dd7caef 0x2dd7c8b3 0x2f648167 0x2f6493af 0x3861e103 0x38622e77 0x3861ff9b 0x38623751 0x386239d1 0x3874ddff 0x3874dcc4)
libc++abi.dylib: terminating with uncaught exception of type NSException
有时在应用重新打开时。
这是我的applicationDidBecomeActive代码:
self.myIdentifier = [[MCPeerID alloc] initWithDisplayName:[self.class createHash:20]];
self.mainSession = [[MCSession alloc] initWithPeer:self.myIdentifier];
self.mainSession.delegate = self;
peerAdvertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:self.myIdentifier discoveryInfo:nil serviceType: service];
peerAdvertiser.delegate = self;
peerBrowser = [[MCNearbyServiceBrowser alloc] initWithPeer:self.myIdentifier serviceType: service];
peerBrowser.delegate = self;
acceptReset = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(reset) userInfo:nil repeats:YES];
acceptPosts = true;
[peerBrowser startBrowsingForPeers];
[peerAdvertiser startAdvertisingPeer];
self.isBrowsing = true;
这是我的applicationWillResignActive的代码:
[acceptReset invalidate];
[peerAdvertiser stopAdvertisingPeer];
[peerBrowser stopBrowsingForPeers];
[self.mainSession disconnect];
self.mainSession = false;
self.isBrowsing = false;
完整的代码可以在这里查看:http://pastebin.com/E3wY6U4N
最佳答案
我记得碰到过这个问题,而快速的解决方法是取消代表,并释放浏览器和广告商。因此,假设您的App Delegate具有每种设置的强大属性,则设置方法如下所示:
self.peerAdvertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:self.myIdentifier discoveryInfo:nil serviceType: service];
self.peerAdvertiser.delegate = self;
self.peerBrowser = [[MCNearbyServiceBrowser alloc] initWithPeer:self.myIdentifier serviceType: service];
self.peerBrowser.delegate = self;
然后,当应用进入后台(或希望停止浏览/广告)时:
self.peerAdvertiser.delegate = nil;
[self.peerAdvertiser stopAdvertisingPeer];
self.peerAdvertiser = nil;
self.peerBrowser.delegate = nil;
[self.peerBrowser stopBrowsingForPeers];
self.peerBrowser = nil;
[self.mainSession disconnect];
我也建议您不要在每次启动应用程序时创建新的
MCPeerID
,因为Multipeer Connectivity具有发现老同辈的习惯,并且您最终会在每次重新启动时发现自己的“前身”。关于ios - MultiPeer MCNearbyBrowserService崩溃,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22888367/