如何让Multipeer Connectivity在不同的设备上持久工作 - Swift

时间:2017-12-05 16:01:24

标签: ios iphone swift3 bluetooth

我在不同设备上遇到与Multipeer Connectivity非常不稳定的连接。

测试:

  • iPhone 6(iOS 11.2)
  • iPad(iOS 9.3.5)
  • iPhone SE(9.3.4)
  • MacBook Pro 2014年中期(High Sierra,10.13.1)

iPhone 6,MacBook和iPad都可以通过wifi连接。但iPad和iPhone 6无法连接蓝牙。然而,iPhone SE可以通过蓝牙连接到iPad。但是iPhone 5无法连接到wifi上的任何设备(尽管它们已被列出,但我无法连接到它们)。

这非常不可靠,我想知道我的代码中是否有任何错误。

代码(Xcode 9.2,Swift):

import UIKit
import MultipeerConnectivity

class ViewController: UIViewController, MCSessionDelegate, MCBrowserViewControllerDelegate {

@IBOutlet weak var label: UILabel!
@IBOutlet weak var textField: UITextField!

@IBAction func send_button(_ sender: Any) {
    sendText(inputText: textField.text!)
}

var peerID: MCPeerID!
var mcSession: MCSession!
var mcAdvertiserAssistant: MCAdvertiserAssistant!

override func viewDidLoad() {
    super.viewDidLoad()

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

}

@IBAction func host_button_action(_ sender: Any) {
    startHosting()
}

@IBAction func join_button_action(_ sender: Any) {
    joinSession()
}

// Host session
func startHosting() {
    mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "hws-kb", discoveryInfo: nil, session: mcSession)
    mcAdvertiserAssistant.start()
}

// Join session
func joinSession() {
    let mcBrowser = MCBrowserViewController(serviceType: "hws-kb", session: mcSession)
    mcBrowser.delegate = self
    present(mcBrowser, animated: true)
}


// Send
func sendText(inputText: String) {
    if mcSession.connectedPeers.count > 0 {

        let myDictionary = ["User" : "player name", "Message" : "\(inputText)"]

            do {
                let data =  NSKeyedArchiver.archivedData(withRootObject:  myDictionary)
                try mcSession.send(data, 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)
            }

    }
}


// Receive data
func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
        DispatchQueue.main.async { [unowned self] in
            print("Getting data: \(data)")

            let myDictionary = NSKeyedUnarchiver.unarchiveObject(with: data) as! NSDictionary
            let message = myDictionary.value(forKey: "Message") as? String

            self.label.text = message
        }
}




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





override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

0 个答案:

没有答案