采用ARSessionDelegate
和MCSessionDelegate
协议,实现它们的委托并将isCollaborationEnabled
实例属性设置为true
:
import RealityKit
import ARKit
import MultipeerConnectivity
class ViewController: UIViewController, ARSessionDelegate, MCSessionDelegate {
@IBOutlet var arView: ARView!
var mcSession: MCSession?
override func viewDidLoad() {
super.viewDidLoad()
arView.session.delegate = self
mcSession!.delegate = self
let config = ARWorldTrackingConfiguration()
config.planeDetection = [.horizontal]
config.isCollaborationEnabled = true
arView.debugOptions = [.showFeaturePoints]
arView.session.run(config)
}
}
然后使用 ARSessionDelegate 和 MCSessionDelegate 的session()
实例方法:
extension ViewController {
let name = UIDevice.current.name
let myPeerID = MCPeerID(displayName: name)
var peers = [MCPeerID]()
peers.append(myPeerID)
func session(_ session: ARSession,
didOutputCollaborationData data: ARSession.CollaborationData) {
self.mcSession = MCSession(peer: myPeerID,
securityIdentity: nil,
encryptionPreference: .required)
do {
try self.mcSession.send(data.collaborationData(),
toPeers: peers,
with: .reliable)
} catch {
print("Get Error while outputting Collaboration Data")
}
}
func session(_ session: MCSession,
didReceive data: Data,
fromPeer peerID: MCPeerID) {
self.arView.session.update(with: data.data())
}
func session(_ session: ARSession,
didRemove anchors: [ARAnchor]) {
for anchor in anchors {
if anchor.sessionIdentifier = session.identifier {
// your anchors here...
}
}
}
}
extension ARSession.CollaborationData {
func collaborationData() -> Data {
let data = Data()
// ...
return data
}
}
extension Data {
func data() -> ARSession.CollaborationData {
let data = ARSession.CollaborationData(coder: nsCoder)
// ...
return data!
}
}
你可以在这里阅读和观看。