I'm trying to download images from firebase storage to display in my collectionview cells, but the images keep appearing in random order in the cells. The cells each have a label that is retrieved from firebase storage (item1, item2 etc) which displays nicely in the correct cell every time. The images stored in firebase storage each have their storage url as a child to their respective item name in the firebase database.
I'm sucesfully able to retrieve each image url, and download all the images and display them in the cells correctly, it's just that they keep appearing in randomized order every time I open the app, so the image does not correspond with the item name label.
I realize i need to asyncronously download the images, so each image finishes loading in the correct cell before continuing to the next, but I'm having trouble doing so. Heres my code so far:
func downloadImg(completion: #escaping (UIImage?) -> ()) {
let ref = Database.database().reference().child("somePath")
ref.observeSingleEvent(of: .value) { (snapshot) in
for item in snapshot.children {
let snap = item as! DataSnapshot
let imageSnap = snap.childSnapshot(forPath: "img/storageUrl")
if let url = imageSnap.value as? String {
let someRef = self.storageRef.reference(forURL: url)
someRef.getData(maxSize: 10 * 10024 * 10024) { data, error in
if let error = error {
print(error)
} else {
let image = UIImage(data: data!)
DispatchQueue.main.async {
completion(image)
}
}
}
}
}
}
}
Then I call my function in the viewdidload:
downloadImg { (completion) in
self.itemPicArray.append(completion!)
self.collectionView?.reloadData()
}
Finally i set my cell imageview to itemPicArray[indexPath.row]
Like I said, this works perfectly except the fact that the images keep showing up randomly. Help very much appreciated!
Your problem is that everytime an image comes in, you reload the entire collection view. Depending on the sizes of the images and the state of the network, the images will come in in a different order almost every time.
Consider downloading all of the images first and then reloading the collection view once. If there are a lot of images, consider paginating your results. You can enumerate the loop and sort the data source array by this original order. I've added a custom data object to help with that.
class CustomObject {
var image: UIImage?
let n: Int
init(image: UIImage?, n: Int) {
self.image = image
self.n = n
}
}
let dispatch = DispatchGroup()
for (n, item) in snapshot.children.enumerated() {
let object = CustomObject(image: nil, n: n) // init custom object with n (image is still nil)
dispatch.enter() // enter dispatch
someRef.getData(maxSize: 10 * 10024 * 10024) { data, error in // download image
if let error = error {
print(error)
} else {
let image = UIImage(data: data!)
object.image = image // inject custom object with image
itemPicArray.append(object) // append to array
}
dispatch.leave() // leave dispatch
}
}
dispatch.notify(queue: .global()) { // dispatch completion
itemPicArray.sort { $0.n < $1.n } // sort by n (original download order)
collectionView.reloadData() // reload collection view
}
Using a model could be a good idea.
struct Image {
var imageName: String
var image: UIImage
}
This way, no matter the order, the item name (image name) and the image will be paired.
Perhaps a better solution now is to configure method downloadImg so that it takes the imageName as a parameter. Then you can call the correct node to get the corresponding storageURL.
func downloadImg(imageName: String, completion: #escaping (Image?) -> ()) {
// Use the parameter to create your database reference
let ref = Database.database().reference().child(imageName)
ref.observeSingleEvent(of: .value) { (snapshot) in
for item in snapshot.children {
let snap = item as! DataSnapshot
let imageSnap = snap.childSnapshot(forPath: "img/storageUrl")
if let url = imageSnap.value as? String {
let someRef = self.storageRef.reference(forURL: url)
someRef.getData(maxSize: 10 * 10024 * 10024) { data, error in
if let error = error {
print(error)
return
}
if let image = UIImage(data: data) {
// Create a variable of type Image (your custom model)
let imageWithName = Image(imageName: imageName, image: image)
completion(imageWithName)
}
}
}
}
}
}
Calling and handling could be done like so:
// Create a variable to hold your item name/image-pairs
var imagesWithNames = [Image]()
let dispatchGroup = DispatchGroup()
// Iterate over your array of item names
for item in itemArray {
dispatchGroup.enter()
downloadImg(item) { (imageWithName) in
self.imagesWithNames.append(imageWithName)
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) { {
self.collectionView?.reloadData()
}
And to populate the collectionView you can go:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! YourCustomCell
// Get the pair at the given index
let imageWithName = self.imagesWithNames[indexPath.row]
DispatchQueue.main.async {
// Set image and item label (example below)
self.yourImageView.image = imageWithName.image
self.yourItemLabel.text = imageWithName.imageName
}
return cell
}
If anyone is having issues with this in the future, use -bsod answer and create a custom object. Also create a variable var counter: Int = 0. Here's how my code looks like Swift 5.X and it works perfectly.
class CustomObject {
var image: UIImage?
let n: Int
init(image: UIImage?, n: Int) {
self.image = image
self.n = n
}
}
func reloadStuff() {
dispatch.notify(queue: .main) {
self.imageArrayCells.sort { $0.n < $1.n }
self.contentViewProfile.collectionView.refreshControl?.endRefreshing()
self.contentViewProfile.collectionView.reloadData()
}
}
for i in 0 ..< self.imageArrayInfo.count {
let object = CustomObject(image: nil, n: i)
let urlString = self.imageArrayInfo[i]
print(object.n)
let url = URL(string: urlString)
self.dispatch.enter()
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
self.dispatch.enter()
guard let data = data, error == nil else {
return
}
guard let image = UIImage(data: data) else {
return
}
object.image = image
self.imageArrayCells.append(object)
self.dispatch.leave()
self.counter += 1
if self.counter == self.imageArrayInfo.count {
for i in 0 ..< self.imageArrayInfo.count {
self.dispatch.leave()
}
self.counter = 0
}
}
task.resume()
}
self.reloadStuff()
Here's what I'm calling in collectionView(cellForItemAt:_)
cell.imageInProfileCollection.image = imageArrayCells[indexPath.row].image
Related
i am trying to fetch images data using URLSession dataTask the urls are fetched from a firebase firestore document that contains each download path using for loop in snapShotDocuments in ascending order, after that the urls are passed into the URLSession dataTask that retrieves the data then appending the result in an array tableCells[] to update a tableview, the problem is the order of the cells in the updated tableview is not the same order of the objects in tableCells array, i am expecting it has something to do with concurrency that i am not aware of here is my code
public func fetchCells() {
guard (UserDefaults.standard.value(forKeyPath: "email") as? String) != nil else {
return
}
spinner.textLabel.text = "Loading"
spinner.position = .center
spinner.show(in: tableView)
db.collection("ads").order(by: "timeStamp").addSnapshotListener { snapshot, error in
self.tableCells = []
guard error == nil , let snapShotDocuments = snapshot?.documents else {
return
}
guard !snapShotDocuments.isEmpty else {
print("snapshot is empty ")
DispatchQueue.main.async {
self.tableView.isHidden = true
self.spinner.dismiss()
}
return
}
for i in snapShotDocuments {
let documentData = i.data()
guard let imageURL = documentData["imageurl"] as? String , let imageStringURL = URL(string: imageURL) else {
print("no url ")
return
}
guard let descriptionLabel = documentData["adDescription"] as? String , let titleLabel = documentData["adTitle"] as? String , let timeStamp = documentData["timeStamp"] as? Double else {
print("error")
return
}
URLSession.shared.dataTask(with: imageStringURL) { data , _ , error in
guard error == nil , let data = data else {
return
}
let image = UIImage(data: data)
let newCell = adoptionCell(cellImage: image, descriptionLabel: descriptionLabel, titleLabel: titleLabel, timePosted: timeStamp, imageUrl: nil)
self.tableCells.append(newCell)
DispatchQueue.main.async {
self.tableView.reloadData()
self.spinner.dismiss()
}
}.resume()
}
}
}
yes correct some image might be loaded faster another is loaded slower. therefore position in final array is changed.
I would rather access tableCells in main thread. here I reload cells in batch. index is used for setting position of the cell in final array.
var tableCells = Array<TableCell?>(repeating: nil, count: snapShotDocuments.count) //preserve space for cells...
var count: Int32 = 0 // actual number of real load tasks
for tuple in snapShotDocuments.enumerated() {
let i = tuple.element
let index = tuple.offset //offset of cell in final array.
let documentData = i.data()
guard let imageURL = documentData["imageurl"] as? String , let imageStringURL = URL(string: imageURL) else {
print("no url ")
return
}
guard let descriptionLabel = documentData["adDescription"] as? String , let titleLabel = documentData["adTitle"] as? String , let timeStamp = documentData["timeStamp"] as? Double else {
print("error")
return
}
count += 1 //increment count as there is new task..
URLSession.shared.dataTask(with: imageStringURL) { data , _ , error in
if error == nil, let data = data {
let image = UIImage(data: data)
let newCell = adoptionCell(cellImage: image, descriptionLabel: descriptionLabel, titleLabel: titleLabel, timePosted: timeStamp, imageUrl: nil)
//self.tableCells.append(newCell)
tableCells[index] = newCell //because array has predefined capacity, thread safe...
}
guard OSAtomicDecrement32(&count) == 0 else { return }
//last task, then batch reload..
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
self.tableCells = tableCells.compactMap { $0 }
self.tableView.reloadData()
self.spinner.dismiss()
}
}.resume()
}
What you have:
for i in snapShotDocuments {
dataTask {
mutate tableCells (append) on background thread <- don't do that, A) not thread safe, and B) append won't happen in order they were dispatched, but the order they came back
dispatch back to main {
reload data <- don't do that, reload the individual rows if needed, or reload everything at the end
}
}
You're enqueuing a number of asynchronous operations that can take varying amount of time to complete. Enqueue them in order 1, 2, 3, 4 and they could come back in order 3, 1, 4, 2, for example.
What you want:
Your model, arranged data instances, let's say an array, of structs, not UITableViewCell's.
for i in snapShotDocuments {
dataTask {
process on background thread, but then
dispatch back to main {
look up in the model, the object for which we have the new data
mutate the model array
then reload row at index path for the row involved
}
}
For study purposes, I'm creating a app to show a list of some star wars ships. It fetches my json (locally) for the ship objects (it has 4 ships for this example).
It's using a custom cell for the table view.
The table populates without problems, if I already have the images downloaded (in user documents) or not.
My starshipData array is populated by my DataManager class by delegate.
I removed some code to make the class smaller, I can show everything if needed.
Ok, so the problem happens (very rarely) when I press the sorting button.
The way I'm doing it is after recovering or downloading the image, I update the image field in starshipData array.
Here is my sorting method, pretty basic.
#objc private func sortByCost(sender: UIBarButtonItem) {
starshipData.sort { $0.costInCredits < $1.costInCredits }
starshipTableView.reloadData()
}
Here are the implementations of the tableView.
First I use the cellForRowAt method to populate the fast/light data.
// MARK: -> cellForRowAt
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "StarshipCell", for: indexPath) as! StarshipCell
let starship = starshipData[indexPath.row]
// update cell properties
cell.starshipNameLabel.text = starship.name
cell.starshipManufacturerLabel.text = starship.manufacturer
cell.starshipCostLabel.text = currencyFormatter(value: starship.costInCredits)
// only populate the image if the array has one (the first time the table is populated,
// the array doesn't have an image, it'll need to download or fetch it in user documents)
if starship.image != nil {
cell.starshipImgView.image = starship.image
}
// adds right arrow indicator on the cell
cell.accessoryType = .disclosureIndicator
return cell
}
Here I use the willDisplay method to download or fetch the images, basically the heavier data.
// MARK: -> willDisplay
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
// update cell image
let cell = cell as! StarshipCell
let imageUrl = starshipData[indexPath.row].imageUrl
let starshipName = starshipData[indexPath.row].name
let index = indexPath.row
// if there isn't any image on the cell, proceed to manage the image
if cell.starshipImgView.image == nil {
// only instantiate spinner on imageView position if no images are set
let spinner = UIActivityIndicatorView(style: .medium)
startSpinner(spinner: spinner, cell: cell)
// manage the image
imageManager(starshipName: starshipName, imageUrl: imageUrl, spinner: spinner, cell: cell, index: index) { (image) in
self.addImageToCell(cell: cell, spinner: spinner, image: image)
}
}
}
Here is where I think the problem is as my knowledge in swift and background threads are still in development.
I found out with print logs that the times the cell doesn't show the correct image is because the array does not have the image for that index, so the cell shows the image from the last time the table was populated/loaded.
I wonder if it's because the background threads didn't have enough time to update the starshipArray with the fetched/downloaded image before the user pushing the sort button.
The thing is, if the table was populated correctly the first time, when the sort button is pushed, the starshipData array should already have all images, as you can see in the imageManager method, after the image is unwrappedFromDocuments, I call updateArrayImage to update the image.
Maybe it's the amount of dispatchesQueues being used? Are the completion handler and dispatchQueues used correctly?
private func imageManager(starshipName: String, imageUrl: URL?, spinner: UIActivityIndicatorView, cell: StarshipCell, index: Int, completion: #escaping (UIImage) -> Void) {
// if json has a string on image_url value
if let unwrappedImageUrl = imageUrl {
// open a background thread to prevent ui freeze
DispatchQueue.global().async {
// tries to retrieve the image from documents folder
let imageFromDocuments = self.retrieveImage(imageName: starshipName)
// if image was retrieved from folder, upload it
if let unwrappedImageFromDocuments = imageFromDocuments {
// TO FORCE THE PROBLEM DESCRIBED, PREVENT ONE SHIP TO HAVE IT'S IMAGE UPDATED
// if (starshipName != "Star Destroyer") {
self.updateArrayImage(index: index, image: unwrappedImageFromDocuments)
// }
completion(unwrappedImageFromDocuments)
}
// if image wasn't retrieved or doesn't exists, try to download from the internet
else {
var image: UIImage?
self.downloadManager(imageUrl: unwrappedImageUrl) { data in
// if download was successful
if let unwrappedData = data {
// convert image data to image
image = UIImage(data: unwrappedData)
if let unwrappedImage = image {
self.updateArrayImage(index: index, image: unwrappedImage)
// save images locally on user documents folder so it can be used whenever it's needed
self.storeImage(image: unwrappedImage, imageName: starshipName)
completion(unwrappedImage)
}
}
// if download was not successful
else {
self.addImageNotFound(spinner: spinner, cell: cell)
}
}
}
}
}
// if json has null on image_url value
else {
addImageNotFound(spinner: spinner, cell: cell)
}
}
Here are some of the helper methods I use on imageManager, if necessary.
// MARK: - Helper Methods
private func updateArrayImage(index: Int, image: UIImage) {
// save image in the array so it can be used when cells are sorted
self.starshipData[index].image = image
}
private func downloadManager(imageUrl: URL, completion: #escaping (Data?) -> Void) {
let session: URLSession = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 5
return URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
}()
var dataTask: URLSessionDataTask?
dataTask?.cancel()
dataTask = session.dataTask(with: imageUrl) { [weak self] data, response, error in
defer {
dataTask = nil
}
if let error = error {
// use error if necessary
DispatchQueue.main.async {
completion(nil)
}
}
else if let response = response as? HTTPURLResponse,
response.statusCode != 200 {
DispatchQueue.main.async {
completion(nil)
}
}
else if let data = data,
let response = response as? HTTPURLResponse,
response.statusCode == 200 { // Ok response
DispatchQueue.main.async {
completion(data)
}
}
}
dataTask?.resume()
}
private func addImageNotFound(spinner: UIActivityIndicatorView, cell: StarshipCell) {
spinner.stopAnimating()
cell.starshipImgView.image = #imageLiteral(resourceName: "ImageNotFound")
}
private func addImageToCell(cell: StarshipCell, spinner: UIActivityIndicatorView, image: UIImage) {
DispatchQueue.main.async {
spinner.stopAnimating()
cell.starshipImgView.image = image
}
}
private func imagePath(imageName: String) -> URL? {
let fileManager = FileManager.default
// path to save the images on documents directory
guard let documentPath = fileManager.urls(for: .documentDirectory,
in: FileManager.SearchPathDomainMask.userDomainMask).first else { return nil }
let appendedDocumentPath = documentPath.appendingPathComponent(imageName)
return appendedDocumentPath
}
private func retrieveImage(imageName: String) -> UIImage? {
if let imagePath = self.imagePath(imageName: imageName),
let imageData = FileManager.default.contents(atPath: imagePath.path),
let image = UIImage(data: imageData) {
return image
}
return nil
}
private func storeImage(image: UIImage, imageName: String) {
if let jpgRepresentation = image.jpegData(compressionQuality: 1) {
if let imagePath = self.imagePath(imageName: imageName) {
do {
try jpgRepresentation.write(to: imagePath,
options: .atomic)
} catch let err {
}
}
}
}
private func startSpinner(spinner: UIActivityIndicatorView, cell: StarshipCell) {
spinner.center = cell.starshipImgView.center
cell.starshipContentView.addSubview(spinner)
spinner.startAnimating()
}
}
To sum all up, here is the unordered table, when you open the app: unordered
The expected result (happens majority of time), after pushing the sort button: ordered
The wrong result (rarely happens), after pushing the sort button: error
I'll gladly add more info if needed, ty!
First, consider move the cell configuration for the UITableViewCell class. something like this:
class StarshipCell {
private var starshipNameLabel = UILabel()
private var starshipImgView = UIImageView()
func configure(with model: Starship) {
starshipNameLabel.text = model.name
starshipImgView.downloadedFrom(link: model.imageUrl)
}
}
Call the configure(with: Starship) method in tableView(_:cellForRowAt:).
The method downloadedFrom(link: ) called inside the configure(with: Starship) is provide by following extension
extension UIImageView {
func downloadedFrom(url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
contentMode = mode
URLSession.shared.dataTask(with: url) { data, response, error in
guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() {
self.image = image
}
}.resume()
}
func downloadedFrom(link: String?, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
if let link = link {
guard let url = URL(string: link) else { return }
downloadedFrom(url: url, contentMode: mode)
}
}
}
I have tableview with label, imageView (for image, gif & video thumbnail). I am sure that doing something wrong and I can't handle its completion handler due to which the app is hanged and gets stuck for a long time.
My model is like,
struct PostiisCollection {
var id :String?
var userID: String?
var leadDetails : NSDictionary?
var company: NSDictionary?
var content: String?
init(Doc: DocumentSnapshot) {
self.id = Doc.documentID
self.userID = Doc.get("userID") as? String ?? ""
self.leadDetails = Doc.get("postiiDetails") as? NSDictionary
self.company = Doc.get("company") as? NSDictionary
self.content = Doc.get("content") as? String ?? ""
}
}
I wrote in my view controller for fetch this,
var postiisCollectionDetails = [PostiisCollection]()
override func viewDidLoad() {
super.viewDidLoad()
let docRef = Firestore.firestore().collection("PostiisCollection").whereField("accessType", isEqualTo: "all_access")
docRef.getDocuments { (querysnapshot, error) in
if let doc = querysnapshot?.documents, !doc.isEmpty {
print("Document is present.")
for document in querysnapshot!.documents {
_ = document.documentID
if let compCode = document.get("company") as? NSDictionary {
do {
let jsonData = try JSONSerialization.data(withJSONObject: compCode)
let companyPost: Company = try! JSONDecoder().decode(Company.self, from: jsonData)
if companyPost.companyCode == AuthService.instance.companyId ?? ""{
print(AuthService.instance.companyId ?? "")
if (document.get("postiiDetails") as? NSDictionary) != nil {
let commentItem = PostiisCollection(Doc: document)
self.postiisCollectionDetails.append(commentItem)
}
}
} catch {
print(error.localizedDescription)
}
DispatchQueue.main.async {
self.tableView.isHidden = false
self.tableView.reloadData()
}
}
}
}
}
}
I need to check for the index path with image view is either image or gif or video with different parameters, I tried with tableview delegate and datasource method by,
extension AllAccessPostiiVC: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return postiisCollectionDetails.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "AllAccessCell", for: indexPath)
let label1 = cell.viewWithTag(1) as? UILabel
let imagePointer = cell.viewWithTag(3) as? UIImageView
let getGif = arrPostiisCollectionFilter[indexPath.row].leadDetails?.value(forKey: "gif") as? NSArray
let getPhoto = arrPostiisCollectionFilter[indexPath.row].leadDetails?.value(forKey: "photo") as? NSArray
let getVideo = arrPostiisCollectionFilter[indexPath.row].leadDetails?.value(forKey: "video") as? NSArray
label1?.text = "\(arrPostiisCollectionFilter[indexPath.row].leadDetails?.value(forKey: "title"))"
if getGif != nil {
let arrGif = getGif?.value(forKey: "gifUrl") as! [String]
print(arrGif[0])
let gifURL : String = "\(arrGif[0])"
let imageURL = UIImage.gifImageWithURL(gifURL)
imagePointer?.image = imageURL
playButton?.isHidden = true
}
if getPhoto != nil {
let arrPhoto = getPhoto?.value(forKey: "photoUrl") as! [String]
print(arrPhoto[0])
let storageRef = Storage.storage().reference(forURL: arrPhoto[0])
storageRef.downloadURL(completion: { (url, error) in
do {
let data = try Data(contentsOf: url!)
let image = UIImage(data: data as Data)
DispatchQueue.main.async {
imagePointer?.image = image
playButton?.isHidden = true
}
} catch {
print(error)
}
})
}
if getVideo != nil {
let arrVideo = getVideo?.value(forKey: "videoUrl") as! [String]
let videoURL = URL(string: arrVideo[0])
let asset = AVAsset(url:videoURL!)
if let videoThumbnail = asset.videoThumbnail{
SVProgressHUD.dismiss()
imagePointer?.image = videoThumbnail
playButton?.isHidden = false
}
}
}
}
If I run, the app hangs in this page and data load time is getting more, some cases the preview image is wrongly displayed and not able to handle its completion
As others have mentioned in the comments, you are better of not performing the background loading in cellFroRowAtIndexPath.
Instead, it's better practice to add a new method fetchData(), where you perform all the server interaction.
So for example:
// Add instance variables for fast access to data
private var images = [UIImage]()
private var thumbnails = [UIImage]()
private func fetchData(completion: ()->()) {
// Load storage URLs
var storageURLs = ...
// Load data from firebase
let storageRef = Storage.storage().reference(forURL: arrPhoto[0])
storageRef.downloadURL(completion: { (url, error) in
// Parse data and store resulting image in image array
...
// Call completion handler to indicate that loading has finished
completion()
})
}
Now you can call fetchData() whenever you would like to refresh data and call tableview.reloadData() within the completion handler. That of course must be done on the main thread.
This approach simplifies your cellForRowAtIndexPath method.
There you can just say:
imagePointer?.image = ...Correct image from image array...
Without any background loading.
I suggest using below lightweight extension for image downloading from URL
using NSCache
extension UIImageView {
func downloadImage(urlString: String, success: ((_ image: UIImage?) -> Void)? = nil, failure: ((String) -> Void)? = nil) {
let imageCache = NSCache<NSString, UIImage>()
DispatchQueue.main.async {[weak self] in
self?.image = nil
}
if let image = imageCache.object(forKey: urlString as NSString) {
DispatchQueue.main.async {[weak self] in
self?.image = image
}
success?(image)
} else {
guard let url = URL(string: urlString) else {
print("failed to create url")
return
}
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) {(data, response, error) in
// response received, now switch back to main queue
DispatchQueue.main.async {[weak self] in
if let error = error {
failure?(error.localizedDescription)
}
else if let data = data, let image = UIImage(data: data) {
imageCache.setObject(image, forKey: url.absoluteString as NSString)
self?.image = image
success?(image)
} else {
failure?("Image not available")
}
}
}
task.resume()
}
}
}
Usage:
let path = "https://i.stack.imgur.com/o5YNI.jpg"
let imageView = UIImageView() // your imageView, which will download image
imageView.downloadImage(urlString: path)
No need to put imageView.downloadImage(urlString: path) in mainQueue, its handled in extension
In your case:
You can implement following logic in cellForRowAt method
if getGif != nil {
let arrGif = getGif?.value(forKey: "gifUrl") as! [String]
let urlString : String = "\(arrGif[0])"
let image = UIImage.gifImageWithURL(urlString)
imagePointer?.image = image
playButton?.isHidden = true
}
else if getPhoto != nil {
let arrPhoto = getPhoto?.value(forKey: "photoUrl") as! [String]
let urlString = Storage.storage().reference(forURL: arrPhoto[0])
imagePointer?.downloadImage(urlString: urlString)
playButton?.isHidden = true
}
elseif getVideo != nil {
let arrVideo = getVideo?.value(forKey: "videoUrl") as! [String]
let urlString = arrVideo[0]
imagePointer?.downloadImage(urlString: urlString)
playButton?.isHidden = false
}
If you have one imageView to reload in tableView for photo, video and gif. then use one image array to store it prior before reloading. So that your main issue of hang or stuck will be resolved. Here the main issue is each time in table view cell collection data is being called and checked while scrolling.
Now I suggest to get all photo, gifs and video (thumbnail) as one single array prior to table view reload try this,
var cacheImages = [UIImage]()
private func fetchData(completionBlock: () -> ()) {
for (index, _) in postiisCollectionDetails.enumerated() {
let getGif = postiisCollectionDetails[index].leadDetails?.value(forKey: "gif") as? NSArray
let getPhoto = postiisCollectionDetails[index].leadDetails?.value(forKey: "photo") as? NSArray
let getVideo = postiisCollectionDetails[index].leadDetails?.value(forKey: "video") as? NSArray
if getGif != nil {
let arrGif = getGif?.value(forKey: "gifUrl") as! [String]
let gifURL : String = "\(arrGif[0])"
self.randomList.append(gifURL)
/////---------------------------
let imageURL = UIImage.gifImageWithURL(gifURL)
self.cacheImages.append(imageURL!)
//////=================
}
else if getVideo != nil {
let arrVideo = getVideo?.value(forKey: "videoUrl") as! [String]
let videoURL: String = "\(arrVideo[0])"
let videoUrl = URL(string: arrVideo[0])
let asset = AVAsset(url:videoUrl!)
if let videoThumbnail = asset.videoThumbnail{
////--------------
self.cacheImages.append(videoThumbnail)
//-----------
}
self.randomList.append(videoURL)
}else if getPhoto != nil {
let arrPhoto = getPhoto?.value(forKey: "photoUrl") as! [String]
let photoURL : String = "\(arrPhoto[0])"
/////---------------------------
let url = URL(string: photoURL)
let data = try? Data(contentsOf: url!)
if let imageData = data {
let image = UIImage(data: imageData)
if image != nil {
self.cacheImages.append(image!)
}
else {
let defaultImage: UIImage = UIImage(named:"edit-user-80")!
self.cacheImages.append(defaultImage)
}
}
//////=================
}
else {
//-----------------
let defaultImage: UIImage = UIImage(named:"edit-user-80")!
self.cacheImages.append(defaultImage)
//--------------------
}
}
completionBlock()
}
After getting all UIImage as array where loop is being called. Now you call this function inside your viewDidLoad. So after all values in images fetched then try to call tableView like this,
override func viewDidLoad() {
self.fetchData {
DispatchQueue.main.async
self.tableView.reloadData()
}
}
}
Now atlast, you may use SDWebImage or any other background image class or download method to call those in tableView cellforRow method,
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// your cell idetifier & other stuffs
if getVideo != nil {
imagePointer?.image = cacheImages[indexPath.row]
playButton?.isHidden = false
}else {
imagePointer?.image = cacheImages[indexPath.row]
// or get photo with string via SdWebImage
// imagePointer?.sd_setImage(with: URL(string: photoURL), placeholderImage: UIImage(named: "edit-user-80"))
playButton?.isHidden = true
}
return cell
}
You're handling data in a totally wrong manner. Data(contentsOf: url!) - This is wrong. You should chache the images and should download it to directory. When you convert something into data it takes place into the memory(ram) and it is not good idea when playing with large files. You should use SDWebImage kind of library to set images to imageview.
Second thing if let videoThumbnail = asset.videoThumbnail - This is also wrong. Why you're creating assets and then getting thumbnail from it? You should have separate URL for the thumbnail image for your all videos in the response of the API and then again you can use SDWebImage to load that thumbnail.
You can use SDWebImage for gif as well.
Alternative of SDWebImage is Kingfisher. Just go through both libraries and use whatever suitable for you.
I'm creating an instagram clone and I'm having a small issue. When the profile page loads, i use a collection view to display all of the images of the posts the user has made, and sort these images by date.
When initially loading, what often happens is that the images will appear out of order. However when i refresh the page, the images display correctly. So when loading instead of getting images (4,3,2,1) I'll get something like (1, 3, 2, 1) then refresh and get the correct order.
When i don't use the sort command, the images always display in the correct order, but i need the newest ones to show up first.
Below is the function i use to observe my post data from Firebase, and append them to the posts array. I use an image cache to load my data.
let posts = [Post]()
func observePosts() {
let currentUser = FIRAuth.auth()?.currentUser?.uid
let ref = FIRDatabase.database().reference().child("user-posts").child(currentUser!)
ref.observe(.childAdded, with: { (snapshot) in
let postId = snapshot.key
let postRef = FIRDatabase.database().reference().child("posts").child(postId)
postRef.observe(.value, with: { (snapshot) in
if let postDict = snapshot.value as? Dictionary<String, AnyObject> {
let post = Post(postKey: postId, postData: postDict)
self.posts.append(post)
self.posts.sort(by: { (post1, post2) -> Bool in
return post1.createdAt! > post2.createdAt!
})
}
self.collectionView?.reloadData()
})
})
}
Loading images using cache:
let imageCache: NSCache<NSString, UIImage> = NSCache()
extension UIImageView {
func loadImagesUsingCacheWith(urlString: String) {
self.image = nil
//check cache for image first
if let cachedImage = imageCache.object(forKey: urlString as NSString) {
self.image = cachedImage
return
} else {
let ref = FIRStorage.storage().reference(forURL: urlString)
ref.data(withMaxSize: 2 * 1024 * 1024, completion: { (data, error) in
if error != nil {
//Handle error
} else {
if let img = UIImage(data: data!) {
self.image = img
imageCache.setObject(img, forKey: urlString as NSString)
}
}
})
}
}
}
cellForItemAt Function:
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCell", for: indexPath) as! HomeCell
let post = posts[indexPath.item]
cell.configureCell(post: post)
return cell
}
Configure Cell function
func configureCell(post: Post) {
if let imgUrl = post.imgUrl {
cellImage.loadImagesUsingCacheWith(urlString: imgUrl)
}
}
UPDATE:
Something super weird happens. In the "cellForItemAt" function, i printed some data from the posts after i declare "let post = posts[indexPath.item]" and the info from the first post always prints to the console twice, while the rest of the data from the posts only prints once. Oddly enough, the picture that is always duplicated when loading the posts is always from the first picture. Any idea as to why this is happening?
I have built my own swift framework for running queries on a MySQL database. I am currently developing a chat application in which I need to display an avatar image for each user who is currently chatting.
I am retrieving the user's profile picture URL from my database and then I need to return a UIImage once I get the profile picture URL. I get the error Unexpected non-void return value in void function. Is there a way to make this easier or bypass this error?
This is my full code:
override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! {
let currentMessage = self.messages[indexPath.row]
if (currentMessage.senderId == self.senderId) {
// Current User sent message
var imageURL: NSURL!
ConnectionManager.sharedInstance.complexQuery("SELECT profile_picture FROM users WHERE username='\(self.senderId)' ", completion: { (result) in
if let results = result as? [[String: AnyObject]] {
for result in results {
if let profilePictureURL = result["profile_picture"] {
print(profilePictureURL)
imageURL = profilePictureURL as! NSURL
let imageData = NSData(contentsOfURL: imageURL)
let image = UIImage(data: imageData!)
// ERROR HERE (line below)
return JSQMessagesAvatarImageFactory.avatarImageWithImage(image, diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault))
}
}
}
})
} else {
var imageURL: NSURL!
ConnectionManager.sharedInstance.complexQuery("SELECT profile_picture FROM users WHERE username='\(currentMessage.senderId)' ", completion: { (result) in
if let results = result as? [[String: AnyObject]] {
for result in results {
if let profilePictureURL = result["profile_picture"] {
print(profilePictureURL)
imageURL = profilePictureURL as! NSURL
let imageData = NSData(contentsOfURL: imageURL)
let image = UIImage(data: imageData!)
// ERROR HERE (line below)
return JSQMessagesAvatarImageFactory.avatarImageWithImage(image, diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault))
}
}
}
})
}
}
It seems that ConnectionManager.sharedInstance.complexQuery is an asynchronous function, so the main thread will continue after calling it, there will be nothing left in this context to receive what will be returned
so, do what ever you want with the image in the callback function "completion"
for example, you may get a reference of your UIImageView and set it's image when you get it, but you need to use another data source delegate method
collectionView(_:cellForItemAtIndexPath:)
Something like this:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(YOUR_ID,
forIndexPath: indexPath) as! YourOwnCell
ConnectionManager.sharedInstance.complexQuery("SELECT profile_picture FROM users WHERE username='\(currentMessage.senderId)' ", completion: { (result) in
if let results = result as? [[String: AnyObject]] {
for result in results {
if let profilePictureURL = result["profile_picture"] {
print(profilePictureURL)
imageURL = profilePictureURL as! NSURL
let imageData = NSData(contentsOfURL: imageURL)
let image = UIImage(data: imageData!)
// Assuming avatarImageWithImage is returning UIImageView
cell.imageView = JSQMessagesAvatarImageFactory.avatarImageWithImage(image, diameter: UInt(kJSQMessagesCollectionViewAvatarSizeDefault))
}
}
}
})
return cell;
}
What you try isn't how asynchronous functions work. It's not how they could work. The whole point of an asynchronous call is that your app can continue running while the asynchronous call continues running in the background. Your complexQuery function returns immediately so that you can continue.
Instead of this function returning the value that you want, your completion code must deposit the value in the right place.