问题
I would like to connect 2 devices using multipeer connectivity framework where one of those devices is running the app in the background, just like Firechat does (I can't confirm this is working, I have installed it on an iPhone 5S and 4, but they just can't find each other - but I have read somewhere this works).
What's the best way to achieve this?
I'm using the following two methods from an example code:
-(void)setupPeerAndSessionWithDisplayName:(NSString *)displayName{
_peerID = [[MCPeerID alloc] initWithDisplayName:displayName];
_session = [[MCSession alloc] initWithPeer:_peerID];
_session.delegate = self;
}
-(void)setupMCBrowser{
_browser = [[MCBrowserViewController alloc] initWithServiceType:@"chat-files" session:_session];
}
-(void)advertiseSelf:(BOOL)shouldAdvertise{
if (shouldAdvertise) {
_advertiser = [[MCAdvertiserAssistant alloc] initWithServiceType:@"chat-files"
discoveryInfo:nil
session:_session];
[_advertiser start];
}
else{
[_advertiser stop];
_advertiser = nil;
}
}
When I'm running the app in the foreground, it finds the other device flawlessly and also connects. But if I put one of the apps into background, the background-app-device is no longer visible.
I have already read this: Can I have a multipeer connectivity session run in the background? - But I can't believe this is not possible without any workaround.
FYI, my app is also using background location updates, if that's relevant...
Thanks!
EDIT: Is there some other way of doing this?? Basically I just want to send a message to the other device (to the one who's app is running in the background) - since Multipeer connectivity doesn't work in the background, can I connect via bluetooth directly for example?
回答1:
Apple have confirmed that "Multipeer Connectivity does not function in the background". The reason is that if your app is suspended then its socket resources can be reclaimed and everything falls apart.
However, it is possible to monitor iBeacons when in the background. Essentially, you set your app up to monitor proximity to a beacon with a specific id. Then, your app that is in the foreground becomes a beacon with that same id. This causes the following app delegate method to be called on the app in the background:
- (void)locationManager:(CLLocationManager *)manager didDetermineState:(CLRegionState)state forRegion:(CLRegion *)region {
UILocalNotification *notification = [[UILocalNotification alloc] init];
if(state == CLRegionStateInside) {
notification.alertBody = NSLocalizedString(@"A nearby app would like to connect", @"");
} else {
return;
}
[[UIApplication sharedApplication] presentLocalNotificationNow:notification];
}
Here you issue a local notification that, when tapped on by the user, will bring your app into the foreground, at which point you can start advertising for a peer-to-peer connection.
来源:https://stackoverflow.com/questions/25514737/multipeer-connectivity-with-one-device-having-app-running-in-background