Reality Kit In Playgrounds App on Ipad

Screenshot of Reality Kit working in Playgrounds App.

This is Proof-of-concept for pulling usdzshare.com (usdz or reality scenes) into Playgrounds app on Ipad.

Copy and paste the code below straight into Playgrounds app. The interactive animated Pig will be pulled from usdzshare.com => Pig Scene hosted on usdzshare.com



import PlaygroundSupport
import RealityKit
import UIKit

class ViewController: UIViewController {
    
    lazy var fileDirectory = NSURL()
    
    override func viewDidAppear(_ animated: Bool) {
        
        self.downloadfile(completion: {(success, fileLocationURL) in
            
            if success {
                
                self.fileDirectory = fileLocationURL! as NSURL

                DispatchQueue.main.async {

                
                let entity = try? Entity.load(contentsOf: self.fileDirectory as URL, withName: "Pig")
                
                        let arscene = ARView(frame: CGRect(x: 0, y: 0, width: 400, height: 400), cameraMode: .ar,automaticallyConfigureSession: true)
                        
                let text3D = MeshResource.generateText(
                    "RealityKit",
                    extrusionDepth: 0.1,
                    font: .systemFont(ofSize: 0.2),
                    containerFrame: .zero,
                    alignment: .left,
                    lineBreakMode: .byTruncatingTail)
                        let text3DMaterial = SimpleMaterial(color: .red, isMetallic: true)
                        let text3DEntity = ModelEntity(mesh: text3D, materials: [text3DMaterial])
                text3DEntity.position = [-0.5,-0.1,0]
                        entity?.position = [0,0,-0.5]
                        
                        let planeAnchor = AnchorEntity(plane: .horizontal)
                
                text3DEntity.generateCollisionShapes(recursive: true)
                
                entity?.generateCollisionShapes(recursive: true)


                // allows you to move around 3D text with your finger 
                arscene.installGestures(for: text3DEntity)
                
                planeAnchor.addChild(entity ?? text3DEntity)
                
                        arscene.scene.addAnchor(planeAnchor)
                        
                planeAnchor.addChild(text3DEntity) 
                        
                        PlaygroundPage.current.setLiveView(arscene)

              }
                        
                
            } else {
                debugPrint("File can't be downloaded")
            }
        })
    }
    
    func downloadfile(completion: @escaping (_ success: Bool, _ filelocation: URL?) -> Void){
        
        let UrlString = "https://usdzshare.com/wp-content/uploads/2020/03/Pig.reality"
        
        let itemUrl = URL(string: UrlString)
        
        // usdz folder url
        let usdzDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        // desination file url
        let destinationUrl = usdzDirectoryURL.appendingPathComponent("Pig.reality")
        // to check file exists before downloading
        if FileManager.default.fileExists(atPath: destinationUrl.path) {
            debugPrint("The file already exists at path")
            completion(true, destinationUrl)
            // if file doesn't exist
        } else {
            // use NSURLSession.sharedSession to download the data asynchronously
            URLSession.shared.downloadTask(with: itemUrl!, completionHandler: { (location, response, error) -> Void in guard let tempLocation = location, error == nil else {return}
                
                do {
                    // after downloading your file you need to move it to your destination url
                    try FileManager.default.moveItem(at: tempLocation, to: destinationUrl)
                    print("File moved to document folder")
                    completion(true, destinationUrl)
                } catch _ as NSError {
                    print("download error")
                    completion(false, nil)
                }
            }).resume()
        }
        
    }
    
}

PlaygroundPage.current.needsIndefiniteExecution = true
PlaygroundPage.current.liveView = ViewController()