如何将变量的值保留在函数外部?

时间:2019-04-09 20:12:18

标签: json swift xcode augmented-reality arkit

我试图在AR文本中显示从JSON获得的值,在DecodeJSON函数中所有这些都可以正常工作,我什至实现了将该值放入普通标签中,但是当我尝试将该值设置为AR文字为空...我该怎么办或我做错了什么?如果您可以帮助我,这将非常有用。

@IBOutlet var sceneView: ARSCNView!
@IBOutlet weak var labelTest: UILabel!

let URL_VWC = "http://w1.doomdns.com:11000/restaguapotable/api/celula/10/sitio/4";

var name :String!

struct JSONTest: Codable {
    let Nombre: String
    let Tiempo: String
}

override func viewDidLoad() {
    super.viewDidLoad()


    // Set the view's delegate
    sceneView.delegate = self

    // Show statistics such as fps and timing information
    sceneView.showsStatistics = true

    // Create a new scene
    let scene = SCNScene()

    // Set the scene to the view
    sceneView.scene = scene
    DecodeJson();


    let text = SCNText(string: name, extrusionDepth: 1.0)
    text.firstMaterial?.diffuse.contents = UIColor.black

    let textNode = SCNNode(geometry: text)
    textNode.position = SCNVector3(0,0, -0.5)
    textNode.scale = SCNVector3(0.02,0.02,0.02)

    sceneView.scene.rootNode.addChildNode(textNode)
}


func DecodeJson(){
    guard let url = URL(string: URL_VWC) else { return }

    // 2
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if error != nil {
            print(error!.localizedDescription)
        }

        guard let data = data else { return }
        do {
            // 3
            //Decode data
            let JSONData = try JSONDecoder().decode(JSONTest.self, from: data)
            // 4
            //Get back to the main queue
            DispatchQueue.main.async {
                self.name = JSONData.Nombre
                self.labelTest.text = self.name
            }

        } catch let jsonError {
            print(jsonError)
        }
        // 5
        }.resume()
}

1 个答案:

答案 0 :(得分:0)

这意味着DecodeJson()在调用self.name = JSONData.Nombre之后返回let text = SCNText(string: name, extrusionDepth: 1.0)

您应该有一个单独的函数,用于在DecodeJson()返回JSON之后设置场景