问题
I´m working with MultipeerConnectivity Apple framework. Connection, advertiser and browser seems to work very well until now but I notice that when my any session connects a peer an then it disconnects for any reason my MCNearbyServiceBrowser
still finding that peer even if it doesn´t exist anymore. Obviously MCSession
reports a not connected status with the peer.
Does anyone has an idea of why this is happening?
I have override the dealloc method in my mc handler class like this:
- (void)dealloc
{
[self.session disconnect];
self.peerId = nil;
self.session = nil;
self.browser = nil;
self.advertiser = nil;
self.session.delegate = nil;
self.browser.delegate = nil;
self.advertiser.delegate = nil;
}
And I also have a tear down method:
- (void)teardownService
{
[self.session disconnect];
self.session = nil;
self.advertiser = nil;
self.browser = nil;
self.session.delegate = nil;
self.browser.delegate = nil;
self.advertiser.delegate = nil;
}
This issue happen with all the devices.
回答1:
I found a really helpful answer at the Apple Dev Forums.
Here the link.
Basically what resolved this issue was recycling the MCPeerID
. When the object is created I serialize it and stored in NSUserDefaults
. And anytime I need it back, like when I tear down the service and start it again I go to the stored object and used it instead of creating a new one.
You can find the next example code in the attached link above:
- (MCPeerID *)peerID {
if (!_peerID) {
_peerID = [MyClassName getRecycledPeerID];
}
return _peerID;
}
+ (MCPeerID *)getRecycledPeerID
{
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// if peer id exists, use that; else create one
if ([defaults objectForKey:kRECYCLED_PEER_ID]) {
NSData *peerIDData = [defaults dataForKey:kRECYCLED_PEER_ID];
return [NSKeyedUnarchiver unarchiveObjectWithData:peerIDData];
}
else {
return [[MCPeerID alloc] initWithDisplayName:[UIDevice currentDevice].name];
}
}
来源:https://stackoverflow.com/questions/26594740/multipeerconnectivity-mcnearbyservicebrowser-constantly-finding-disconnected-p