I am stuck on how to fix something. I currently have an iPhone app that is literally Instagram but just horizontally and paging, where users see friends photos.
Now I have created a function that grabs images from firebase and puts them in an array. Now this works great along with performing a shared URLSession. I noticed my app was running high on memory usage so I added a URLcache, and set the limit on how large it can get, actually is sort of high now that I think about it. But I am still getting high memory (171mb)-, and that's only loading 4 images usage which makes it seem like I am not caching the data right.
I am still learning how to work with URLSessions and also caching so this also might contribute to a problem if I set it up wrong. Online people were saying use SDWebImage, but really, users won't scroll down or be able to scroll down fast because first paging's enabled and also it's horizontal. Here is some of my code, please tell me what you think I should do.
urlcache in
viewDidLoad() { //probably too high..
let memoryCapacity = 500 * 1024 * 1024
let diskCapacity = 500 * 1024 * 1024
let urlCache = URLCache(memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: "myDiskPath")
URLCache.shared = urlCache
}
// cellforrow
if posts.count != nil {
let pozt = posts[indexPath.row].pathToImage
let url = URL(string: pozt!)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil {
print(error?.localizedDescription as Any)
return
}
DispatchQueue.main.async {
cell.myImage.image = UIImage(data: data!)
self.loader.stopAnimating()
}
}).resume()
}
cell.myImage.image = UIImage(named: imaqes[0])
return cell
}
I think almost all programmers on swift using libraries to cache images. I use KingFisher instead of SDWebImage. Its lightweight and simple to use.
To install:
Podfile:
pod 'Kingfisher'
In terminal:
pod install
In swift file:
import Kingfisher
In your case use it next way:
// cellforrow
if posts.count != nil {
let pozt = posts[indexPath.row].pathToImage
let url = URL(string: pozt!)
DispatchQueue.main.async {
cell.myImage.kf.setImage(with: url!) //Using kf for caching images
}
}
return cell
Maybe you should use .kf.setImage
with comletion handler to remove loader. You should get the idea.
Hope it helps
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.