我试图在Swift 3中编写这个代码,它适用于多人游戏

时间:2017-08-17 22:17:10

标签: swift

此代码是旧版本的Swift 2.我试图在Swift 3中编写它,但我遇到了问题。这是一款多人游戏。我遇到了问题"让userInfo"。我收到此错误"额外参数' userInfo' "在通话中

import UIKit
import MultipeerConnectivity

class MPCHander: NSObject, MCSessionDelegate {
    var peerID:MCPeerID!
    var session:MCSession!
    var browser:MCBrowserViewController!
    var advertiser:MCAdvertiserAssistant? = nil

    func setupPeerWithDisplayName (displayName:String){
        peerID = MCPeerID(displayName: displayName)
    }

    func setupSession(){
        session = MCSession(peer: peerID)
        session.delegate = self
    }

    func setupBrowser(){
        browser = MCBrowserViewController(serviceType: "my-game", session: session)
    }

    func advertiseSelf(advertise:Bool){
        if advertise{
            advertiser = MCAdvertiserAssistant(serviceType: "my-game", discoveryInfo: nil, session: session)
            advertiser!.start()
        }else{
            advertiser!.stop()
            advertiser = nil
        }
    }

    func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
        let userInfo = ["peerID":peerID,"state":state.rawValue]
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            NSNotificationCenter.defaultCenter().postNotificationName("MPC_DidChangeStateNotification", object: nil, userInfo: userInfo)
        })

    }

    func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
        let userInfo = [data:"data" , peerID:"peerID"] as [AnyHashable : String]
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MPC_DidChangeStateNotification"), object: nil, userInfo: userInfo)
    }

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

    }

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

    }

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

1 个答案:

答案 0 :(得分:0)

你应该发布整个控制台输出。

问题出在NSNotificationCenter上。将您的func session(_:, peer:, didChange:)方法换成:

func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
    let userInfo = ["peerID":peerID,"state":state.rawValue] as! [AnyHashable : String]
    DispatchQueue.main.async {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "MPC_DidChangeStateNotification"), object: nil, userInfo: userInfo)
    }
}