gpt4 book ai didi

ios - 在 swift 4 中显示 MCBrowserViewController

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:30:33 25 4
gpt4 key购买 nike

所以,我一直试图让 MCBrowserViewController 出现,但我没有成功。我正在尝试在我为 iOS 开发的应用程序中创建它。谁能帮忙?这是我的代码:

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

如果你想知道,我做了很多研究,但我并不是真的理解这一点,我也看过 apple 的文档,但这并没有给我一个合适的例子。我以前问过这样的问题,但没有得到可供引用的答案。因此,如果可以的话,能否发布您的答案,但附上我当前的代码,好吗?

最佳答案

您的 playground 代码有点乱,但这里有一个更清晰的示例,说明如何设置此类类:

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!
}
}

关于ios - 在 swift 4 中显示 MCBrowserViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47997102/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com