1

How to extract data from networking class into variable in same class so that it can be accessed from other class in ios

Code for Networking Class


import Foundation

struct NetworkManager {
    func fetchData(url : String) {
        print("Neeraj here")
        let sessionURL = URL(string: url)
        let session = URLSession(configuration: .default)
        let dataTask = session.dataTask(with: sessionURL!) { (data, response, error) in
            if error == nil {
                if let safeData = data {
                    if let parsedData = self.parseData(data : safeData) {
                        print("got data")
                    }
                }
            }
            else {
                print("error in data task is \(String(describing: error))")
            }
        }
        dataTask.resume()
        
    }
    
    func parseData(data : Data) -> DataModel? {
        let decoder = JSONDecoder()
        do {
            let decodedData = try decoder.decode(DataModel.self, from: data)
            return decodedData
        } catch {
            print("error while parsing data \(error)")
            return nil
        }
    }
}

Here where i am getting data, i want that data to be stored somewhere or in same class so that i can access it from class i am calling this method fetchData

  • Does this answer your question? [Returning data from async call in Swift function](https://stackoverflow.com/questions/25203556/returning-data-from-async-call-in-swift-function) – Joakim Danielson Dec 26 '20 at 18:44

1 Answers1

1

You can use the closure to return the value out of the function. This practice is functional programming, almost using for async function.

func fetchData(url: String, completion: (DataModel?) -> ()) {
    ...
    if let parsedData = self.parseData(data : safeData) {
        print("got data")
        completion(parsedData)
    } else {
        completion(nil)
    }
}

And then, to use it:

NetworkManager().fetchData(url: "https://google.com", completion: { data in
    // handle the “data”
})
Hai Pham
  • 193
  • 5
  • When i am using this i am getting an error in line ```let dataTask = session.dataTask(with: sessionURL!) { (data, response, error) in``` that "Escaping closure captures non-escaping parameter 'completion". What does this mean – Neeraj Gupta Dec 26 '20 at 18:27
  • I am missing the @escaping. You can refer this post: https://stackoverflow.com/a/46245943/10267768 – Hai Pham Dec 26 '20 at 18:32
  • yes, thanks for help. I appreciate your help – Neeraj Gupta Dec 26 '20 at 19:15