如何使用swift 4查看Multipeer Connectivity框架中的MCBrowserViewController

Posted

技术标签:

【中文标题】如何使用swift 4查看Multipeer Connectivity框架中的MCBrowserViewController【英文标题】:How to view the MCBrowserViewController in the Multipeer Connectivity framework using swift 4 【发布时间】:2017-12-18 23:22:06 【问题描述】:

我一直在尝试让 Multipeer 连接在 SWIFT 4 中工作,但我无法查看 MCBrowserViewController,我是 swift 新手,谁能帮忙?我也打算做到这一点,https://www.hackingwithswift.com/example-code/system/how-to-create-a-peer-to-peer-network-using-the-multipeer-connectivity-framework 所以我的目标是通过编程方式建立点对点连接。

这是我的代码:

import UIKit
import PlaygroundSupport
import MultipeerConnectivity
var peerID: MCPeerID!
var mcSession: MCSession!
var mcAdvertiserAssistant: MCAdvertiserAssistant!
var browser: MCNearbyServiceBrowser!
var foundPeers = [MCPeerID]()
class viewcontroller: UIViewController 
override func viewDidLoad() 


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)
    


    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)

  

   PlaygroundPage.current


func presentViewControllerAsSheet(_ viewController: MCBrowserViewController) 


【问题讨论】:

表是什么意思 我的意思是 MCBrowserViewController。我看不到。 我一直在看这个页面developer.apple.com/documentation/multipeerconnectivity/…但我不太明白, 我已经给出了答案试试看你是否得到了预期的结果。 【参考方案1】:

你没有得到 BrowserViewController 因为你没有声明它。 移除 MCNearbyServiceBrowser。

步骤:

声明一个MCBrowserViewController

类型的变量
  var serviceBrowser : MCBrowserViewController!

然后开始浏览同行

func startBrowsingForPeer()  
    serviceBrowser = MCBrowserViewController(serviceType: locationServiceType, session: session)

    serviceBrowser.delegate = self


当你想显示 MCBrowserViewController 时调用 startBrowsingForPeer()

实现MCBrowserViewControllerDelegate及其功能

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

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

   


【讨论】:

我会把这个放在哪里,我把它放在课外,我这样做有错吗? 我的意思是在课堂内 类中的前两个代码。课外扩展 好吧,我想我明白了 等哪个课?我有 2 个【参考方案2】:

这是我的代码。它说在扩展中, serviceBrowser 有错误。它不断将其更正为 NetServiceBrowser。

import UIKit
import PlaygroundSupport
import MultipeerConnectivity

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





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)



        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) 
    serviceBrowser.dismiss(animated: true, completion: nil)


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





PlaygroundPage.current

【讨论】:

以上是关于如何使用swift 4查看Multipeer Connectivity框架中的MCBrowserViewController的主要内容,如果未能解决你的问题,请参考以下文章

尝试使用 Multipeer Connectivity Swift 3 Xcode8 传递 UIALERT 时出现多个错误

swift Multipeer Connectivity,使用邀请处理程序取消邀请

swift Swift - Multipeer连接

Swift2.0 Multipeer Connectivity 无法连接

使用Multipeer Connectivity(Swift 2)从发件人的目标iPhone中部分接收音频文件

在 Swift 中通过 Multipeer Connectivity 临时同步两个 iOS 设备