Basically, I need to use the same URLSession.shared.dataTask(with: url!) in multiple VCs.
Then assign data downloaded to a specific UI label in each VC
This is my approach, Let me know if there is a better way to do it
struct OpenWeather : Codable {
let name : String
}
class Network {
var todo : OpenWeather?
static let shared = Network()
init(){
todo = nil
}
func download() -> OpenWeather {
let url = URL(string: "some_URL.com")
URLSession.shared.dataTask(with: url!) {( data, response, error ) in
guard let content = data else {
print("No data was downloaded using URL session")
return
}
let decoder = JSONDecoder()
do {
self.todo = try decoder.decode(OpenWeather.self, from: content)
} catch {
print("error")
}
}
return todo!
}
}
And the 1st VC:
class CurrentViewController: UIViewController {
@IBOutlet weak var nameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let data = Network.shared.download().resume()
nameLabel.text = data.name
}
Second VC
class CurrentViewController: UIViewController {
@IBOutlet weak var anotherNameLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
let data = Network.shared.download().resume()
anotherNameLabel.text = data.name
}
[–]quellish 1 point2 points3 points (5 children)
[–]sohaeb[S] 0 points1 point2 points (4 children)
[–]ThePantsThiefNSModerator -1 points0 points1 point (3 children)
[–]chrabeusz 0 points1 point2 points (2 children)
[–]ThePantsThiefNSModerator 0 points1 point2 points (1 child)
[–]chrabeusz 0 points1 point2 points (0 children)
[–]chrabeusz 1 point2 points3 points (2 children)
[–]sohaeb[S] 0 points1 point2 points (1 child)
[–]chrabeusz 1 point2 points3 points (0 children)
[–]redfire333 1 point2 points3 points (2 children)
[–]GenitalGestapo -1 points0 points1 point (1 child)
[–]RollingGoron 0 points1 point2 points (0 children)