Reputation: 187
I have a very simple iOS app that pulls images from firebase, adds them to an array, then puts them in a collection view with a url session. Only one problem, the view that holds the collection view of images is a separate view from the main view, so each time the user clicks to the view, I watch the memory usage sore. The when you click back, the memory does not change. Each time the view is pushed, the memory usage keeps rising. I have never experienced this problem before when I did the url session in the main view, but now I have issues in the separate view. Here is my code for downloading the image:
for grabbing image:
let ref = firdatabase.dadatabase.reference
ref.child("Pages").queryOrderedByKey.observeSingleEvent(type: .value, snapshot in
if let pages = snapshot.value as? [String : AnyObject] {
for (_, vale) in pages {
let newPage = page()
If let url = vale["url"] as? String {
newpage.url = url
pagers.append(new page)
}
}
collection view.reloadData()
)}
nsurlsession:
if pagers.count != 0 {
let post = pagers[indexPath.row].url
let url = URL(string: post!)
let session = URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if let errer = error {
print(errer.localizedDescription)
}
DispatchQueue.main.async {
cell.imageViewPage.image = UIImage(data: data!)
}
})session.resume()
}
return cell
Now here is the problem though, the memory keeps rising and not ever dropping.
I really need your help to find a solution to this problem because I have no idea how, and have never had this problem before.Thank you. I am hoping there is a simple solution to this problem.
Upvotes: 0
Views: 810
Reputation: 131418
It isn't clear that you have a memory leak. Just because memory use goes up does not mean you have a memory leak.
If you load images from a remote URL and save them in an array then your memory use will go up.
If you leave the view controller and discard the array and your memory use goes back down, you don't have a memory leak.
Note that your code is installing your images into table view/collection view cells but not saving them anywhere. That means that if the user scrolls a cell off-screen, then scrolls back to it, you'll download it again.
Instead, I would suggest writing your code to save your images to disk as files. You can create a hash of the file URL and use that as the filename. Check to see if the file is already on disk, (probably in your app's caches directory) and load it from from disk if so. If not, use an URLSession download object and save the file to your hash filename in the caches directory when the download is complete, and then install it in the target cell.
Upvotes: 1
Reputation: 15015
I think you need to invalidate your session task once it completes to avoid memory leak
urlSession.invalidateAndCancel()
Upvotes: 0