0

I am completely new to Swift and I am fetching a json object from an http request and after I access the value from json I am not able to display it as label.text = myvariable. When I do this after this:

if let parseJSON = json {
                    
                    // Now we can access value of First Name by its key
                    let firstNameValue = parseJSON["firstName"] as? String
                    print("firstNameValue: \(firstNameValue)")
                }

I get an error message Cannot find 'firstNameValue' in scope. Here the complete code:

    override func viewDidAppear(_ animated: Bool) {
        /// HTTP Request to MSSQL Server
        
         let myUrl = URL(string: "http://13.69.140.186/select.php?user=jerome.sarcosi@email.com");
 
         var request = URLRequest(url:myUrl!)
         
         request.httpMethod = "POST"// Compose a query string
         
         let postString = "";
         
         request.httpBody = postString.data(using: String.Encoding.utf8);
         
         let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
             
             if error != nil
             {
                 print("error=\(error)")
                 return
             }
             
             // You can print out response object
             print("response = \(response)")

             // Let's convert response sent from a server side script to a NSDictionary object:
             do {
                 let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                 
                 if let parseJSON = json {
                     
                     // Now we can access value of First Name by its key
                     let make = parseJSON["make"] as? String
                     print("make: \(make)")
                 }
             } catch {
                 print(error)
             }
         }
         task.resume()
        label.center = self.view.center
        label.text = "I want the variable here"
        label.text = make // ERROR: Cannot find 'make' in scope

The print command makes my string go to the console (which is fine), but also I want the json output string as in the image below:

enter image description here

alexcc
  • 9
  • 1
  • 5
  • The variable you define inside do block is will not access out side the do..catch block so you need to make the variable global to use. – Hardik Thakkar Oct 20 '22 at 05:56

0 Answers0