在swift 4中显示MCBrowserViewController

时间:2017-12-27 18:39:00

标签: ios swift4 multipeer-connectivity

所以,我一直试图让MCBrowserViewController出现,但我没有运气。我正在尝试在我正在为iOS开发的appp中创建它。有人可以帮忙吗?这是我的代码:

import UIKit
import PlaygroundSupport
import MultipeerConnectivity

var peerID: MCPeerID!
var mcSession: MCSession!
var mcAdvertiserAssistant: MCAdvertiserAssistant!
var foundPeers = [MCPeerID]()



PlaygroundPage.current.needsIndefiniteExecution = true

class viewcontroller: UIViewController {
override func viewDidLoad() {
var serviceBrowser : MCBrowserViewController!
func startBrowsingForPeer()  {
    serviceBrowser = MCBrowserViewController(serviceType: "hws-ridleyn", session: mcSession)

    serviceBrowser.delegate.self

}



peerID = MCPeerID(displayName: UIDevice.current.name)
mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .none)
mcSession.delegate.self

class ViewController: UIViewController, MCSessionDelegate, MCBrowserViewControllerDelegate {



let session = MCSession(peer: peerID, 
                        securityIdentity: nil, 
                        encryptionPreference: .none)



func session(_ session: MCSession, peer peerID: MCPeerID, didChange 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)")
    }
}

func browser(browser: MCNearbyServiceBrowser!, foundPeer peerID: MCPeerID!, withDiscoveryInfo info: [NSObject : AnyObject]!) {
    foundPeers.append(peerID)

    print(browser)
    browser.startBrowsingForPeers()

}


func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
    if let image = UIImage(data: data) {
        DispatchQueue.main.async { [unowned self] in
            print("image recieved")
        }
    }
}
func sendImage(img: UIImage) {
    if mcSession.connectedPeers.count > 0 {
        if let imageData = UIImagePNGRepresentation(img) {
            do {
                try mcSession.send(imageData, toPeers: mcSession.connectedPeers, with: .reliable)
            } catch let error as NSError {
                let ac = UIAlertController(title: "Send error", message: error.localizedDescription, preferredStyle: .alert)
                ac.addAction(UIAlertAction(title: "OK", style: .default))
                present(ac, animated: true)
            }
        }
    }
}

func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
}
func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
}
    func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {
    }
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
            dismiss(animated: true)
        }
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
    dismiss(animated: true)
}


func startHosting(action: UIAlertAction!) {
    mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "hws-ridleyn", discoveryInfo: nil, session: mcSession)
    mcAdvertiserAssistant.start()
}
func joinSession(action: UIAlertAction!) {
    let mcBrowser = MCBrowserViewController(serviceType: "hws-ridleyn", session: mcSession)
    mcBrowser.delegate = self
    present(mcBrowser, animated: true)
}

let vc = UIToolbar(frame: CGRect(x: 100, y: 100, width: 200, height: 200))


// your view controller here
}


let vcc = ViewController()
vcc.startHosting(action: nil)
ViewController.startHosting(vcc)

   }
}
extension viewcontroller : MCBrowserViewControllerDelegate {
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
    dismiss(animated: true, completion: nil)
}

func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
    dismiss(animated: true, completion: nil)

   }

}


PlaygroundPage.current

如果你想知道,我已经做了很多研究,但我并没有真正理解这一点,我也看过苹果的文档,但这并没有给我一个合适的例子。之前我问过这样的问题,但我没有得到一个可供我参考的答案。所以,如果可以的话,你可以发布你的答案,但请附上我当前的代码吗?

1 个答案:

答案 0 :(得分:1)

你的游乐场代码有点混乱,但这里有一个更清晰的例子来说明如何设置这种类型的类:

import UIKit
import MultipeerConnectivity

class MPCPeripheralViewController: UIViewController {

    private let peerID = MCPeerID(displayName: UIDevice.current.name)
    private var mcBrowser: MCBrowserViewController?
    private var mcSession: MCSession!
    private var outputStream: OutputStream?

    // MARK: Class methods
    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a session - Using the arguments you require
        mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required)
        mcSession.delegate = self
    }

    // Hook this up to a button - use it to show the browser
    @IBAction func connectButtonPressed(_ sender: UIBarButtonItem) {
        // The MCBrowserView is nicely set up for us in situation - so we don't need any custom views
        mcBrowser = MCBrowserViewController(serviceType: "StackOverflow", session: mcSession)

        guard let mcBrowser = mcBrowser else {
            print("Couldn't create mcBrowser!")
            return
        }

        mcBrowser.delegate = self
        present(mcBrowser, animated: true)
    }

    func joinSession() {
        guard mcSession.connectedPeers.count > 0 else {
            print("No connected peers")
            return
        }

        outputStream = try? mcSession.startStream(withName: "control", toPeer: mcSession.connectedPeers.first!)

        guard let outputStream = outputStream else {
            print("Output stream is nil")
            return
        }

        outputStream.delegate = self
        outputStream.schedule(in: RunLoop.main, forMode:RunLoopMode.commonModes)
        outputStream.open()

        // From now on you can write to the stream!
    }
}

// MARK: MCBrowserViewControllerDelegate
extension MPCPeripheralViewController: MCBrowserViewControllerDelegate {

    func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
        dismiss(animated: true)
        joinSession()
    }

    func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
        dismiss(animated: true)
    }
}

extension MPCPeripheralViewController: MCSessionDelegate {
    func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
        switch state {
        case .connected:
            print("Connected: \(peerID.displayName)")
        case .connecting:
            print("Connecting: \(peerID.displayName)")
        case .notConnected:
            print("Not Connected: \(peerID.displayName)")
        }
    }

    // You probably aren't going to receive data on a peripheral connection!
    func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {}

    func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {}

    func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {}

    func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {}
}

extension MPCPeripheralViewController: StreamDelegate {
}






// The Central device!

import UIKit
import MultipeerConnectivity

class MPCCentralViewController: UIViewController {

    // MARK: Properties
    var mcAdvertiserAssistant: MCAdvertiserAssistant!
    var peerID: MCPeerID = MCPeerID(displayName: UIDevice.current.name)
    var mcSession: MCSession!
    var stream: InputStream?

    override func viewDidLoad() {
        super.viewDidLoad()

        mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required)
        mcSession.delegate = self
    }

    // Hook this up!
    @IBAction func findDeviceButtonPressed(_ sender: Any) {
        startHosting()
    }

    func startHosting() {
        mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "StackOverflow", discoveryInfo: nil, session: mcSession)
        mcAdvertiserAssistant.delegate = self
        mcAdvertiserAssistant.start()
    }
}

// MARK: MCSessionDelegate
extension MPCCentralViewController: MCSessionDelegate {
    func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
        // Utility debug method - check how our session is doing
        switch state {
        case .connected:
            print("Connected: \(peerID.displayName)")
        case .connecting:
            print("Connecting: \(peerID.displayName)")
        case .notConnected:
            print("Not Connected: \(peerID.displayName)")
        }
    }

    func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
        print("Received some data")
    }

    func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
        // Stop advertising once we're receiving a stream
        mcAdvertiserAssistant.stop()

        print("Received stream!")
        stream.delegate = self
        stream.schedule(in: RunLoop.main, forMode:RunLoopMode.commonModes)
        stream.open()
    }

    func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {}

    func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {}
}

// MARK: MCAdvertiserAssistantDelegate
extension MPCCentralViewController: MCAdvertiserAssistantDelegate {}

// MARK: StreamDelegate
extension MPCCentralViewController: StreamDelegate {

    func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
        // Deal with your snazzy new stream here!
    }
}