1

I'm trying to return json data from an api call. I'm able to access the json data successfully but am struggling to find a way / the best way to return it for access in my app. Thanks for any ideas!

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // make the api call and obtain data
        let data = self.loadData()
        print("inside viewDidLoad", data) // prints 'inside viewDidLoad emptyString'
    }
    
    func loadData() -> String {
        var circData = "emptyString"
        let session = URLSession.shared
        let url = URL(string: "https://us-east-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/cirdata-khyvx/service/cirData/incoming_webhook/cirlAPI")!
        let task = session.dataTask(with: url, completionHandler: { data, response, error in
            if let json = try? JSONSerialization.jsonObject(with: data!, options: []) {
//                print("json: ", json) // prints the whole json file, verifying the connection works. Some 300kb of data.
//                print("json file type: ", type(of: json)) // prints '__NSArrayI'
                
                let jsonString = "\(json)"
                circData = jsonString
//                print("circData", circData) // prints the whole json file, verifying that the json string has been assigned to 'circData'
            }
        })
        task.resume()
//        print("after: ", circData) // prints 'after: emptyString'. It's as if the reassignment didn't take place.
        return circData
    }
}
Sandy Lord
  • 21
  • 1
  • 2

1 Answers1

3

You can't return a value synchronously becuase the api call that is fetching json data is asynchronous. You need to use a completion handler instead.

You can put breakpoints in different places inside the code to understand how the flow executes.

import UIKit

class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.loadData(completion: { [weak self] (result, error) in
            if let error = error {
                print(error.localizedDescription)
            }
            if let result = result {
                print(result)
            }
        })
    }
    
    func loadData(completion: @escaping (_ data: Any?, _ error: Error?) -> Void) {
        let url = URL(string: "https://us-east-1.aws.webhooks.mongodb-realm.com/api/client/v2.0/app/cirdata-khyvx/service/cirData/incoming_webhook/cirlAPI")!
        let task = URLSession.shared.dataTask(with: url, completionHandler: { data, response, error in
            if let error = error {
                completion(nil, error)
                return
            }
            do {
                if let data = data {
                    let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments])
                    completion(json, nil)
                } else {
                    completion(nil, nil)
                }
            } catch {
                completion(nil, error)
            }
        })
        task.resume()
    }
}
Tarun Tyagi
  • 9,364
  • 2
  • 17
  • 30