Reputation: 1451
I have an URLSession
that is fired from viewDidLoad
. It returns JSON which contains URL for an image. So, to get that image I fire another URLSession
right from the completion block of the JSON Decoder which is called from the completion block of the first URLSession
. Here is the code for that:
//THIS IS CALLED FROM viewDidLoad()
let task = urlSession.dataTask(with: url!) { (data, response, error) in
guard error == nil else {
print ("Error while fetching collections: \(String(describing: error))")
return
}
if let data = data, let string = String(data: data, encoding: .utf8) {
print (string)
URL_Request_Handler.parsingJSON(fromData: data, completion: {(result) in
if let result = result {
print ("JSON IS CONVERTED")
print (result)
//This method creates another session and fires it
self.getFinalCollectionFromResult(result)
}
})
}
}
task.resume()
And here is the getFinalCollectionFromResult
method:
private func getFinalCollectionFromResult(_ result: Result_Collection) {
let task = URLSession.shared.dataTask(with: URL(string:result.cover_photo.url)!, completionHandler: { (data, response, error) in
if error != nil {
print("Errror")
}
if let data = data, let image = UIImage(data: data) {
DispatchQueue.main.async {
self.collection = Collection(title: result.title, image: image)
self.collectionViewLayout.collectionView?.reloadData()
}
}
})
task.resume()
}
Is it ok to create another session right from the completion block of the first one?
Upvotes: 1
Views: 39
Reputation: 817
Yes, it's perfectly fine.
But one suggestion: you should use a downloadTask for the image instead of a dataTask. Apple says the dataTask is meant for small bits of data, not large amounts of data like you'd get from an image, and downloadTask would give you the ability to pause/resume the download if you wanted to add that functionality down the road.
Upvotes: 1