Reputation:
I have been using this code to establish a proper connection. I have tried both iPhone Simulator and Physical Device. I could not connect it properly. As in it shows its state as "Connecting..." and just directly goes to "Not Connected" state. I have explored a lot, and didn't find anything useful which would solve this issue. Also i read some questions in Apple Developer Forum that so many people have faced the same issue. But there is no proper solution yet. Please check the code. And thanks in advance.
import UIKit
import MultipeerConnectivity
//MARK: MCNearbyServiceAdvertiserDelegate
extension ViewController : MCNearbyServiceAdvertiserDelegate
{
// Incoming invitation request. Call the invitationHandler block with YES
// and a valid session to connect the inviting peer to the session.
func advertiser(advertiser: MCNearbyServiceAdvertiser, didReceiveInvitationFromPeer peerID: MCPeerID, withContext context: NSData?, invitationHandler: (Bool, MCSession) -> Void)
{
invitationHandler(true, self.session) // Accepting an invitation
// self.serviceBrowser.stopBrowsingForPeers()
}
// Advertising did not start due to an error.
func advertiser(advertiser: MCNearbyServiceAdvertiser, didNotStartAdvertisingPeer error: NSError)
{
print("\(error.localizedDescription)")
}
}
//MARK: MCNearbyServiceBrowserDelegate
extension ViewController : MCNearbyServiceBrowserDelegate
{
// Found a nearby advertising peer.
func browser(browser: MCNearbyServiceBrowser, foundPeer peerID: MCPeerID, withDiscoveryInfo info: [String : String]?)
{
browser.invitePeer(peerID, toSession: self.session, withContext: nil, timeout: 10) // Inviting a peer to connect to my session
// self.serviceAdvertiser.stopAdvertisingPeer()
}
// A nearby peer has stopped advertising.
func browser(browser: MCNearbyServiceBrowser, lostPeer peerID: MCPeerID)
{
print("Lost")
}
// Browsing did not start due to an error.
func browser(browser: MCNearbyServiceBrowser, didNotStartBrowsingForPeers error: NSError)
{
print("\(error.localizedDescription)")
}
}
//MARK: MCSessionDelegate
extension ViewController : MCSessionDelegate
{
// Remote peer changed state.
func session(session: MCSession, peer peerID: MCPeerID, didChangeState state: MCSessionState)
{
switch state
{
case MCSessionState.Connected:
print("Connected: \(peerID.displayName)")
case MCSessionState.Connecting:
print("Connecting: \(peerID.displayName)")
case MCSessionState.NotConnected:
print("Not Connected: \(peerID.displayName)")
}
}
// Received data from remote peer.
func session(session: MCSession, didReceiveData data: NSData, fromPeer peerID: MCPeerID)
{
dispatch_async(dispatch_get_main_queue()) {
let str = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
print("Value recieved : \(str)")
}
}
// Received a byte stream from remote peer.
func session(session: MCSession, didReceiveStream stream: NSInputStream, withName streamName: String, fromPeer peerID: MCPeerID)
{
}
// Start receiving a resource from remote peer.
func session(session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, withProgress progress: NSProgress)
{
}
// Finished receiving a resource from remote peer and saved the content
// in a temporary location - the app is responsible for moving the file
// to a permanent location within its sandbox.
func session(session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, atURL localURL: NSURL, withError error: NSError?)
{
}
// Made first contact with peer and have identity information about the
// remote peer (certificate may be nil).
func session(session: MCSession, didReceiveCertificate certificate: [AnyObject]?, fromPeer peerID: MCPeerID, certificateHandler: (Bool) -> Void)
{
}
}
//MARK: ViewController
class ViewController: UIViewController {
// View Did Load
override func viewDidLoad() {
super.viewDidLoad()
self.start()
}
// User clicked on a button, send value alvin to all connected devices
@IBAction func helloclicked(sender: UIButton)
{
self.sendValuesToPeer("alvin")
}
private enum EHRServiceType : String
{
case Update = "HelloUpdate"
}
var myOwnPeerId : MCPeerID!
// Browser
var advertiserAssistant : MCAdvertiserAssistant!
// For finding the devices
var serviceAdvertiser : MCNearbyServiceAdvertiser!
// For listening to devices
var serviceBrowser : MCNearbyServiceBrowser!
// Session
// var session : MCSession!
lazy var session : MCSession = {
let session = MCSession(peer: self.myOwnPeerId, securityIdentity: nil, encryptionPreference: MCEncryptionPreference.Optional)
session.delegate = self
return session
}()
func start() {
self.myOwnPeerId = MCPeerID(displayName: "Alvin \(UIDevice.currentDevice().name)")
// Advertising
self.serviceAdvertiser = MCNearbyServiceAdvertiser(peer: self.myOwnPeerId, discoveryInfo: nil, serviceType: EHRServiceType.Update.rawValue)
// Browsing
self.serviceBrowser = MCNearbyServiceBrowser(peer: self.myOwnPeerId, serviceType: EHRServiceType.Update.rawValue)
self.advertiserAssistant = MCAdvertiserAssistant(serviceType: EHRServiceType.Update.rawValue, discoveryInfo: nil, session: self.session)
// Session
// self.session = MCSession(peer: self.myOwnPeerId, securityIdentity: nil, encryptionPreference: MCEncryptionPreference.Required)
// Session
// self.session.delegate = self
// Browsing
self.serviceBrowser.delegate = self
self.serviceBrowser.startBrowsingForPeers() // Starting browsing...
// Avertising
self.serviceAdvertiser.delegate = self
self.serviceAdvertiser.startAdvertisingPeer() // Starting advertising...
self.advertiserAssistant.start()
}
override func viewDidAppear(animated: Bool) {
// let browser = MCBrowserViewController(browser: self.serviceBrowser, session: self.session)
// self.presentViewController(browser, animated: true, completion: nil)
}
//MARK: Send values to peer
func sendValuesToPeer(name : String)
{
if self.session.connectedPeers.count > 0
{
let value = name.dataUsingEncoding(NSUTF8StringEncoding)
do
{
try self.session.sendData(value!, toPeers: self.session.connectedPeers, withMode: MCSessionSendDataMode.Reliable)
}
catch
{
}
}
else
{
print("No peers")
}
}
}
I have tried so many situations also, Like without encryption, with encryption, with same project target ( While using iPhone Simulator in two computer ), By stopping advertising when finding a device, by stopping browsing whenever an invitation sent. But none of these alternatives solved my issue, it is still in "Connecting..." and directly goes to "Not Connected". Please let me know your thoughts.
Upvotes: 2
Views: 1449
Reputation: 2999
First check you are in the same wifi network.
But don't forget bulutooth does not work in simulator.
also, device and simulator is completely okay. I am working with multiplier for several months. I noticed connecting - Disconnected state only when both devices/peers are in the different wifi/bluetooth network.
If all these are Okay. Then
read this and get sample project.
Upvotes: 1