我有一个运行中的简单HTTP服务器,我试图从我的本地服务器中获取此Scenekit,但它向我显示NIL错误或错误加载场景。我不明白如何从我的简单本地主机加载此模型。如何配置我的代码,以便能够从远程或本地服务器获取任何Scenekit。
预先感谢
do {
let shipScene = try SCNScene(url: URL(fileURLWithPath: "http://localhost:8080/chair.scn") , options: nil)
// Set the scene to the view
sceneView.scene = shipScene
let shipNode = shipScene.rootNode.childNodes.first!
shipNode.position = SCNVector3Zero
shipNode.position.z = 0.15
shipNode.position.y = 0
shipNode.position.x = 0
let action = SCNAction.repeatForever(SCNAction.rotate(by: .pi, around: SCNVector3(0, 1, 0), duration: 5))
shipNode.runAction(action)
planeNode.addChildNode(shipNode)
node.addChildNode(planeNode)
} catch {
print("ERROR loading scene")
}
答案 0 :(得分:2)
正如@Prashant所说,在使用它之前,您需要先下载模型。
因此,您需要做的第一件事就是创建一个URLSession来下载文件,例如:
/// Downloads An SCNFile From A Remote URL
func downloadSceneTask(){
//1. Get The URL Of The SCN File
guard let url = URL(string: "http://localhost:8080/chair.scn") else { return }
//2. Create The Download Session
let downloadSession = URLSession(configuration: URLSession.shared.configuration, delegate: self, delegateQueue: nil)
//3. Create The Download Task & Run It
let downloadTask = downloadSession.downloadTask(with: url)
downloadTask.resume()
}
}
然后我们将参考URLSessionDownloadDelegate
,例如:
class ViewController: UIViewController, URLSessionDownloadDelegate { }
现在我们已将代表连接起来,我们需要使用以下callback
将下载的文件复制到设备的Documents Directory
:
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
//1. Create The Filename
let fileURL = getDocumentsDirectory().appendingPathComponent("chair.scn")
//2. Copy It To The Documents Directory
do {
try FileManager.default.copyItem(at: location, to: fileURL)
print("Successfuly Saved File \(fileURL)")
//3. Load The Model
loadModel()
} catch {
print("Error Saving: \(error)")
}
}
请注意,在函数中,我正在使用以下帮助程序方法来获取文档目录:
/// Returns The Documents Directory
///
/// - Returns: URL
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
一旦文件被下载并复制到整个文件中,我们将像这样调用loadModel function
(3):
/// Loads The SCNFile From The Documents Directory
func loadModel(){
//1. Get The Path Of The Downloaded File
let downloadedScenePath = getDocumentsDirectory().appendingPathComponent("chair.scn")
do {
//2. Load The Scene Remembering The Init Takes ONLY A Local URL
let modelScene = try SCNScene(url: downloadedScenePath, options: nil)
//3. Create A Node To Hold All The Content
let modelHolderNode = SCNNode()
//4. Get All The Nodes From The SCNFile
let nodeArray = modelScene.rootNode.childNodes
//5. Add Them To The Holder Node
for childNode in nodeArray {
modelHolderNode.addChildNode(childNode as SCNNode)
}
//6. Set The Position
modelHolderNode.position = SCNVector3(0, 0, -1.5)
//7. Add It To The Scene
self.augmentedRealityView?.scene.rootNode.addChildNode(modelHolderNode)
} catch {
print("Error Loading Scene")
}
}
希望有帮助...