iOS Multipeer Connectivity both Advertiser and Browser - ios

My setup is this: I have somewhere between 0 and 8 devices running at a time, and devices can be added or removed at any time.
I want to use the iOS 7 Multipeer framework to connect them. I have this working in a controlled environment, I can start 1-7 devices in advertiser mode, then start one in browser mode and they all link up.
What I'm unsure of is how I should know if the device needs to be in advertiser or browser mode when I start it? I've tried defaulting to advertiser mode for X seconds then switching to browser, the problem with this is that it's possible that all the devices started at the same time and turn off advertiser mode at the same time.
I've also considered running devices in both advertiser and browser mode, but the initial problem is that the device discovers itself. Also I believe I have 1 less device to connect this way.
I'm sure there's a recommended way to set this up but I've been unable to find anything that doesn't assume there's a set browser and advertiser, anyone have suggestions for this?

It is easy to make all devices both advertiser and browsers, and it's a normal behavior (I'm pretty sure there's a mention of this in the documentation, I'll search it and add the link later).
I haven't had problems with the device discovering itself, maybe you're creating two peerIDs for the same device?
You may like to check PLPartyTime's implementation of this. It just has a few simple checks to see if it needs to connect/accept a connection.
Advertiser Delegate
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser
didReceiveInvitationFromPeer:(MCPeerID *)peerID
withContext:(NSData *)context
invitationHandler:(void(^)(BOOL accept, MCSession *session))invitationHandler
{
// Only accept invitations with IDs lower than the current host
// If both people accept invitations, then connections are lost
// However, this should always be the case since we only send invites in one direction
if ([peerID.displayName compare:self.peerID.displayName] == NSOrderedDescending)
{
invitationHandler(YES, self.session);
}
}
Browser Delegate
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info
{
// Whenever we find a peer, let's just send them an invitation
// But only send invites one way
// TODO: What if display names are the same?
// TODO: Make timeout configurable
if ([peerID.displayName compare:self.peerID.displayName] == NSOrderedAscending)
{
NSLog(#"Sending invite: Self: %#", self.peerID.displayName);
[browser invitePeer:peerID
toSession:self.session
withContext:nil
timeout:10];
}
}
You may also want to check out my fork, which is a little bit smaller and both browser and advertiser are separate objects.

Related

Disable connection alert Multipeer Connectivity

I'd like to use the Multipeer Connectivity functionality for my app. Brief intro to the functionality of the app:
The app should scan for other devices running the app (in background), connect to them and transfer a bit of data. All without interaction with the user.
Question: is it possible to connect to other devices using multipeer but without having to show the alert view that another device wants to connect and forcing the user to accept or decline the connection? Is there a way who I can programmatically accept all incoming connections from other devices? If so, how?
Thanks a lot in advance!
You have two questions here:
The app should scan for other devices running the app (in background)
The answer here is NO - MPC does not work in the background (see this so response)
For your second question:
is it possible to connect to other devices using multipeer but without having to show the alert
The answer is Yes .. all the detail you need can be found in the apple docs. Here's some snippets on what I do:
On one device - start the browser
_serviceBrowser = [[MCNearbyServiceBrowser alloc] initWithPeer:_peerID
serviceType:_sessionName];
[_serviceBrowser startBrowsingForPeers];
On the other device - start the advertiser
_serviceAdvertiser = [[MCNearbyServiceAdvertiser alloc] initWithPeer:_peerID
discoveryInfo:nil
serviceType:_sessionName];
[_serviceAdvertiser startAdvertisingPeer];
These services implement delegate functions to advise your app of a possible connection. Here the browser is advised of an advertiser and now invites the peer to join in a session
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info
{
[browser invitePeer:peerID toSession:_session withContext:nil timeout:30.0];
}
The advertiser then responds
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer: (MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void(^)(BOOL accept, MCSession *session))invitationHandler
{
invitationHandler(YES, _session);
}
Now you will receive a session delegate call to advise you of the state of your peer connectivity. At this point you should be connected - no "real" user interaction required.
- (void)session:(MCSession *)session peer:(MCPeerID *)peerID didChangeState:(MCSessionState)state

Reconnecting to disconnected peers

I'm using the iOS 7 Multipeer framework in my app but I'm experiencing a problem with devices disconnecting. If I open the app in two devices: device A and device B the two devices connect to each other automatically. However, after several seconds device A disconnects from device B. i.e. At first the connection is like this:
A ---> B
A <--- B
After several seconds:
A ---> B
A B
Device A maintains it's connection but device B get's a MCSessionStateNotConnected.
This means that A can send data to B but B can't reply. I tried to get around this by checking if the device is connected and if it's not, re-initiating the connection using:
[browser invitePeer:peerID toSession:_session withContext:Nil timeout:10];
But the didChangeState callback just get's called with MCSessionStateNotConnected.
Strangely if I send app A to the background, then re-open it, B reconnects to it and the connection is maintained.
The Multipeer API (and documentation) seems a bit sparse so I was assuming that it would just work. In this situation how should I re-connect the device?
I was having the same problem, and it seems to have been related to my app browsing and advertising at the same time, and two invitations being sent/accepted. When I stopped doing this and let one peer defer to the other for invitations the devices stayed connected.
In my browser delegate I'm checking the hash value of the discovered peer's displayName and only sending an invitation if my peer has a higher hash value:
Edit
As pointed out by #Masa the hash value of an NSString will be different on 32 and 64 bit devices, so it's safer to use the compare: method on displayName.
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info {
NSLog(#"Browser found peer ID %#",peerID.displayName);
//displayName is created with [[NSUUID UUID] UUIDString]
BOOL shouldInvite = ([_myPeerID.displayName compare:peerID.displayName]==NSOrderedDescending);
if (shouldInvite){
[browser invitePeer:peerID toSession:_session withContext:nil timeout:1.0];
}
else {
NSLog(#"Not inviting");
}
}
As you say, the documentation is sparse so who knows what Apple really wants us to do, but I've experimented with both sending and accepting invitations using a single session, and also creating a new session for each invitation accepted/sent, but this particular way of doing things has given me the most success.
For anyone interested, I created MCSessionP2P, a demo app that illustrates the ad-hoc networking features of MCSession. The app both advertises itself on the local network and programmatically connects to available peers, establishing a peer-to-peer network. Hat tip to #ChrisH for his technique of comparing hash values for inviting peers.
I liked ChrisH's solution, which reveals the key insight that only one peer should connect to the other peer, not both. Mutual connection attempts results in mutual disconnection (though not that a single-sided connection actually is, counter-intuitively, a mutual connection in terms of status and communication, so that works fine).
However, I think a better approach than one peer inviting is for both peers to invite but only one peer to accept. I use this method now and it works great, because both peers have an opportunity to pass rich information to the other via the context parameter of the invitation, as opposed to having to rely on scant information available in the foundPeer delegate method.
Therefore, I recommend a solution like so:
- (void)browser:(MCNearbyServiceBrowser *)browser foundPeer:(MCPeerID *)peerID withDiscoveryInfo:(NSDictionary *)info
{
[self invitePeer:peerID];
}
- (void)advertiser:(MCNearbyServiceAdvertiser *)advertiser didReceiveInvitationFromPeer:(MCPeerID *)peerID withContext:(NSData *)context invitationHandler:(void (^)(BOOL accept, MCSession *session))invitationHandler
{
NSDictionary *hugePackageOfInformation = [NSKeyedUnarchiver unarchiveObjectWithData:context];
BOOL shouldAccept = ([hugePackageOfInformation.UUID.UUIDString compare:self.user.UUID.UUIDString] == NSOrderedDescending);
invitationHandler(shouldAccept && ![self isPeerConnected:peerID], [self openSession]);
}
I have the same issue when devices trying to connect to each other at the same time and I don't know how to find a reason because we don't have any errors with MCSessionStateNotConnected.
We can use some crafty way to solve this issue:
Put into txt records ( discovery info ) a time [[NSDate date] timeIntervalSince1970] when app started. Who started first - send invitation to others.
But I think it's not a right way ( if apps start at the same time, unlikely... :) ). We need to figure out the reason.
This is the result of a bug, which I've reported to Apple. I've explained how to fix it in my response to another question: Why does my MCSession peer disconnect randomly?
I have not flagged these questions for merging, because while the underlying bug and solution are the same, the two questions describe different problems.
Save the hash of the peer B. Using a timer check the state of the connection continuously if is not connected try to reconnect with each given period of time.
According to apple document Choosing an inviter when using Multipeer Connectivity
“In iOS 7, sending simultaneous invites can cause both invites to fail, leaving both peers unable to communicate with each other.”
But iOS 8 has fixed it.
It seems that the .notConnected message is a false positive in that the device is still receiving data. So, I manually updated local connection state to .connected
It was hard to factor out other state from other examples. So, I wrote a bare bones MCSession example for SwiftUI, here: MultiPeer

Peripheral name doesn't comply to NameKey

I have an app that simulates heart rate monitor peripheral (The peripheral app).
I also have an app that receives the data and present it (The central app).
The central app decided to connect to the discovered peripheral based on its name.
The problem is that both app work perfectly good, except that the name is always "iPhone".
The advertising is done this way:
- (IBAction)switchChanged:(id)sender
{
if (self.advertisingSwitch.on) {
NSDictionary *advData =
#{CBAdvertisementDataLocalNameKey:#"Custom Name",
CBAdvertisementDataServiceUUIDsKey:#[[CBUUID UUIDWithString:#"180D"]]};
[self.peripheralManager startAdvertising:advData];
NSLog(#"Advertising");
}
else {
[self.peripheralManager stopAdvertising];
[[self timerInterval] invalidate];
NSLog(#"Stopped advertising");
}
}
But on the central side, inside
- (void) centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)aPeripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
The name property never changed.
Is there anything that should be done?
What I have observed with CBPeripheral.name is that the device will, in fact, set the name to the name you select with CBAdvertisementDataLocalNameKey. This name is not persistent, though. If you disconnect the master and reconnect,the name will generally have been switched to "iPhone". If the peripheral disconnects due to an error, I have seen it reconnect with the correct peripheral name, but a new UUID.
There may be other situations where the name also switches to iPhone.
This appears to be a bug in iOS. I'm looking for confirmation before reporting it.
CBAdvertisementDataLocalNameKey only change kCBAdvDataLocalName in advertisementData.
When you nslog advertisementData, you will see some data like this:
{
kCBAdvDataIsConnectable = 1;
kCBAdvDataLocalName = Custom Name;
kCBAdvDataServiceUUIDs = (
"FB694B90-F49E-4597-8306-171BBA78F846"
);
}
Unfortunately, there is no other way to set the peripheral name. iPhone will always have the name: iPhone.
The advertisement is probably correctly seen on the central side. You may check by NSLogging the advertisementData. However, if you rely on the peripheral.name property, then that will either be empty (if you connect first) or contain the "iPhone" string.
I remember it is used to happen to me and I figured it was something to do with the way Core Bluetooth handles caching and service discovery. What Happened to me was that at first I received a default name like iPhone, iPad or nothing at all. But then after discovering services or trying to establish a connection the key magically changes to the value I had set on the other end.
Moreover, it seems it only happens the first time, afterwards, even between launches and subsequent runs of the app Core Bluetooth will try its best to return those values to you on the advertisement stage even on first discovery, but those might as well be outdated values.
my current implementation looks as follows:
NSString * baconName = [[UIDevice currentDevice] name];
NSDictionary *advertisementData = #{CBAdvertisementDataServiceUUIDsKey:#[[CBUUIDUUIDWithString:BACON_SERVICE_UUID]],
CBAdvertisementDataLocalNameKey:baconName};
And It just works for me, iPhones love Bacon, everybody does ;).
Hence, the best way to ensure you get any data you want, is to create another characteristic to transmit your flag and do constant discoveries of services and characteristics for Peripherals you are discovering, and accordingly minimise the discovery of existing or cached peripherals by caching or keeping a reference to them, CB is supposed to do this for ya, and they do their best effort but only you know the business logic of your app and what is important to you. I am overly paranoid and keep references to the discovered peripherals I am interested all the time. That is just me: it ensures I have the right information, and that I minimise scanning and constant re discovery of services and characteristics.
I Hope this helps.
In most such applications instead of identifying the peripheral by name, the client app should be identifying it by a service ID, and the server (peripheral), should be providing a either a standard service ID, as defined at bluetooth.org, or a proprietary service ID/name.
I have the same problem. I argee with Mike, this really seems like bug in IOS. If you discover your peripheral with TI multitool (for example) first, then your device will be discovered as you setuped in CBAdvertisementDataLocalNameKey.
to Dan1one:
you should use [[UIDevice currentDevice] model], not name, to get the string same to default.

iOS GameCenter connection from different networks

I have made an iOS multiplayer GameCenter game, but right before publishing found an issue I don't know how to solve. In coding process I used Ray Wenderlich tutorial http://www.raywenderlich.com/3276/how-to-make-a-simple-multiplayer-game-with-game-center-tutorial-part-12
GameCenter view controller is shown, connection creates and game can be played until both devices are on the same Wifi network.
If I turn off Wifi on my phone and use 3G network, then try to start new game - in that case connection isn't made anymore. Both devices find each other, but hangs on "Connecting..." screen. It looks like that
- (void)match:(GKMatch *)theMatch player:(NSString *)playerID didChangeState:(GKPlayerConnectionState)state
is not called. Any ideas how to solve it or at least understand, where exactly is the problem?
I think that in your particular case the problem is that your 3G ISP restricts connections from necessary ports. The Apple docs say:
To use Game Center ... port forwarding must be enabled for ports 443 (TCP), 3478-3497 (UDP), 4398 (UDP), 5223 (TCP), 16384-16387 (UDP), and 16393-16472 (UDP)
I faced this issue too when trying to play on iPad connected via bluetooth to iPhone: there was "Connecting..." screen on each device.
But when I use built-in iPad 3G (with a different tariff plan) everything goes fine.
Just remind, in a normal match-making scenario match:player:didChangeState: may not be called. You should also check match.expectedPlayerCount:
- (void)matchmakerViewController:(GKMatchmakerViewController *)viewController didFindMatch:(GKMatch *)theMatch {
//...
if (theMatch.expectedPlayerCount == 0) {
NSLog(#"Ready to start match!");
}
}
Also I expected a similar problem with "Connecting..." screen, but on Wifi network.
And it was reproduced only on iOS6 and after I tried rematch via -[GKMatch rematchWithCompletionHandler:^(GKMatch *match, NSError *error) {}] before.
One device hanged on "Connecting..." screen but on the other matchmakerViewController:didFindMatch: was successfully called, but what is interesting is that match.expectedPlayerCount was 0 and match.playerIDs array was empty at the same time.
I think such error occurred because I tried to find a new match while previous match tried to reconnect on background thread in the same time. And because of that new match was obtained corrupted.
The decision is to wait for rematchCompletion being called and only then try to find new match. There is no interface in GKMatch to cancel rematch, so I use [[GKMatchmaker sharedMatchmaker] cancel] and after several seconds rematchCompletion is called with error and we are ready to start finding new match.
Also I figured out that old unsued GKMatch instances are not deallocated and continue to live somewhere in GameKit framework. And they may probably cause problems if the work with them is not finished correctly (i.e. not disconnected, or rematch is not canceled in my case ). So do not forget to call -[GKMatch disconnect] and finish any other kind of work before removing the last strong reference to the match object .

GKSession mode peer: How to automatically connect two peers without any button / confirmation?

I want to establish a bluetooth connection between 2 iPhones with a GKSession without GKPeerPickerController and without pushing any "connect button" on both sides.
I'm using the following code:
currentSessionAuto = [[GKSession alloc] initWithSessionID: #"instant-friend-auto"
currentSessionAuto.delegate = self;
currentSessionAuto.available = YES;
currentSessionAuto.disconnectTimeout = 5;
[currentSessionAuto setDataReceiveHandler: self withContext:nil];
When the application is starting on both sides, the
- (void)session:(GKSession *)session peer:(NSString *)peerID didChangeState:(GKPeerConnectionState)state is called on both sides with the state "GKPeerStateAvailable".
With a "classic" app, a popup is displayed on both side to ask for connection and most of the time, both "users" does not click on the connect button on the same time.
If I want to have an "Automatic connection" I need a mechanism to only initiate the session on 1 side, because without this mechanism two sessions will be initiated and errors occur.
Any idea / help ?
Take a look at GKSessionP2P, a demo app that illustrates the ad-hoc networking features of GKSession. The app both advertises itself on the local network and automatically connects to available peers, establishing a peer-to-peer network.
Here's an idea: have the peer with the lowest peerID connect. You'll have to convert the PeerID string to an int and compare, but it should be a great tie breaker.

Resources