Search code examples
swiftaugmented-realityarkitusdz

How to load a usdz model and textures from a remote server using ARKit?


How to load a usdz model and textures from a remote server using ARKit?

As in the example below:

let myURL = NSURL(string: "https://mywebsite.com/vase.scn")

guard let scene = try? SCNScene(url: myURL! as URL, options: nil) else {
    return
}

let node = scene.rootNode.childNode(withName: "vase", recursively: true)

let transform = queryResult.worldTransform
let thirdColumn = transform.columns.3
node!.position = SCNVector3(thirdColumn.x, thirdColumn.y, thirdColumn.z)
self.sceneView.scene.rootNode.addChildNode(node!)

Solution

  • I found solution as in the below:

    1. Download model and save

      func downloadModel() {
      
          guard let url = URL(url: originalURL) else { return }
          let urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: OperationQueue())
          let downloadTask = urlSession.downloadTask(with: url)
          downloadTask.resume()
      }
      
      extension ARViewController: URLSessionDownloadDelegate {
      
           public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {          print("locationUrl:", location.path)
      
            // create destination URL with the original file name
               guard let url = downloadTask.originalRequest?.url else { return }
               let documentsPath = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
              let destinationURL = documentsPath.appendingPathComponent(url.lastPathComponent)
      
            // delete original copy
               try? FileManager.default.removeItem(at: destinationURL)
      
            // copy from temp to Document
        do {
              try FileManager.default.copyItem(at: location, to: destinationURL)
              self.originalURL = destinationURL
              print("originalURL:", originalURL!.path)
      
         } catch let error {
          print("Copy Error: \(error.localizedDescription)")
          }
        }
      }
      
    2. Load usdz model and textures

      func addItem(queryResult: ARRaycastResult) {
      
          let url = URL(string: originalURL!.path)
          let mdlAsset = MDLAsset(url: url!)
          mdlAsset.loadTextures()
          let scene = SCNScene(mdlAsset: mdlAsset)
          let node = scene.rootNode.childNode(withName: "model", recursively: true)
          let transform = queryResult.worldTransform
          let thirdColumn = transform.columns.3
          node!.position = SCNVector3(thirdColumn.x, thirdColumn.y, thirdColumn.z)
          self.sceneView.scene.rootNode.addChildNode(node!)
      
      }