I want to call TableViewData Sources method for Seeting up Ui after it has been fethced from parse . With this i am able to fetch
func loadImages() {
var query = PFQuery(className: "TestClass")
query.orderByDescending("objectId")
query.findObjectsInBackgroundWithBlock ({(objects:[AnyObject]!, error: NSError!) in
if(error == nil){
self.getImageData(objects as [PFObject])
}
else{
println("Error in retrieving \(error)")
}
})//findObjectsInBackgroundWithblock - end
}
func getImageData(objects: [PFObject]) {
for object in objects {
let thumbNail = object["image"] as PFFile
println(thumbNail)
thumbNail.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) -> Void in
if (error == nil) {
var imageDic = NSMutableArray()
self.image1 = UIImage(data:imageData)
//image object implementation
self.imageResources.append(self.image1!)
println(self.image1)
println(self.imageResources.count)
}
}, progressBlock: {(percentDone: CInt )-> Void in
})//getDataInBackgroundWithBlock - end
}//for - end
self.tableView.reloadData()
But not able to populate these fetched data to tableview like this
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("in table view")
println(self.imageResources.count)
return imageResources.count+1;
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
var (title, image) = items[indexPath.row]
cell.loadItem(title: title, image: image)
println("message : going upto this line")
println(self.imageResources.count)
var (image1) = imageResources[indexPath.row]
cell.loadItem1(image1: image1)
return cell
}
Then on loaditem i am trying to show up the images and i have writen my own array to populate to the image array but i am geeting a zero value when populating so not able to set it up
Any Help is much appreciated!
You have several problems, all related to concurrency - your load is occurring in the background and in parallel.
The first problem is the use of self.image1 as a temporary variable in the loading process - this variable may be accessed concurrently by multiple threads. You should use a local variable for this purpose.
Second, you are appending to self.imageResources from multiple threads, but Swift arrays are not thread safe.
Third, you need to call reload on your tableview after you have finished loading all of the data, which isn't happening now because you call it while the background operations are still taking place.
Finally, your getImageData function is executing on a background queue, and you must perform UI operations (such as reloading a table) on the main queue.
The simplest option is to change get thumbnail loading to synchronous calls - This means that your thumbnails will load sequentially and may take a bit longer that the multiple parallel tasks but it is easier to manage -
func getImageData(objects: [PFObject]) {
for object in objects {
let thumbNail = object["image"] as PFFile
println(thumbNail)
let imageData? = thumbNail.getData
if (imageData != nil) {
let image1 = UIImage(data:imageData!)
//image object implementation
self.imageResources.append(image1!)
println(self.imageResources.count)
}
}//for - end
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
A more sophisticated approach would be to use a dispatch group and keep the parallel image loading. In order to do this you would need to guard the access to the shared array
Related
I have a pretty elaborate problem and I think someone with extensive async knowledge may be able to help me.
I have a collectionView that is populated with "Picture" objects. These objects are created from a custom class and then again, these objects are populated with data fetched from Parse (from PFObject).
First, query Parse
func queryParseForPictures() {
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, err: NSError?) -> Void in
if err == nil {
print("Success!")
for object in objects! {
let picture = Picture(hashtag: "", views: 0, image: UIImage(named: "default")!)
picture.updatePictureWithParse(object)
self.pictures.insert(picture, atIndex: 0)
}
dispatch_async(dispatch_get_main_queue()) { [unowned self] in
self.filtered = self.pictures
self.sortByViews()
self.collectionView.reloadData()
}
}
}
}
Now I also get a PFFile inside the PFObject, but seeing as turning that PFFile into NSData is also an async call (sync would block the whole thing..), I can't figure out how to load it properly. The function "picture.updatePictureWithParse(PFObject)" updates everything else except for the UIImage, because the other values are basic Strings etc. If I would also get the NSData from PFFile within this function, the "collectionView.reloadData()" would fire off before the pictures have been loaded and I will end up with a bunch of pictures without images. Unless I force reload after or whatever. So, I store the PFFile in the object for future use within the updatePictureWithParse. Here's the super simple function from inside the Picture class:
func updateViewsInParse() {
let query = PFQuery(className: Constants.ParsePictureClassName)
query.getObjectInBackgroundWithId(parseObjectID) { (object: PFObject?, err: NSError?) -> Void in
if err == nil {
if let object = object as PFObject? {
object.incrementKey("views")
object.saveInBackground()
}
} else {
print(err?.description)
}
}
}
To get the images in semi-decently I have implemented the loading of the images within the cellForItemAtIndexPath, but this is horrible. It's fine for the first 10 or whatever, but as I scroll down the view it lags a lot as it has to fetch the next cells from Parse. See my implementation below:
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Constants.PictureCellIdentifier, forIndexPath: indexPath) as! PictureCell
cell.picture = filtered[indexPath.item]
// see if image already loaded
if !cell.picture.loaded {
cell.loadImage()
}
cell.hashtagLabel.text = "#\(cell.picture.hashtag)"
cell.viewsLabel.text = "\(cell.picture.views) views"
cell.image.image = cell.picture.image
return cell
}
And the actual fetch is inside the cell:
func loadImage() {
if let imageFile = picture.imageData as PFFile? {
image.alpha = 0
imageFile.getDataInBackgroundWithBlock { [unowned self] (imageData: NSData?, err: NSError?) -> Void in
if err == nil {
self.picture.loaded = true
if let imageData = imageData {
let image = UIImage(data: imageData)
self.picture.image = image
dispatch_async(dispatch_get_main_queue()) {
UIView.animateWithDuration(0.35) {
self.image.image = self.picture.image
self.image.alpha = 1
self.layoutIfNeeded()
}
}
}
}
}
}
}
I hope you get a feel of my problem. Having the image fetch inside the cell dequeue thing is pretty gross. Also, if these few snippets doesn't give the full picture, see this github link for the project:
https://github.com/tedcurrent/Anonimg
Thanks all!
/T
Probably a bit late but when loading PFImageView's from the database in a UICollectionView I found this method to be much more efficient, although I'm not entirely sure why. I hope it helps. Use in your cellForItemAtIndexPath in place of your cell.loadImage() function.
if let value = filtered[indexPath.row]["imageColumn"] as? PFFile {
if value.isDataAvailable {
cell.cellImage.file = value //assign the file to the imageView file property
cell.cellImage.loadInBackground() //loads and does the PFFile to PFImageView conversion for you
}
}
I'm querying images from my Parse backend, and displaying them in order in a UITableView. Although I'm downloading and displaying them one at a time, they're appearing totally out of order in my table view. Each image (album cover) corresponds to a song, so I'm getting incorrect album covers for each song. Would someone be so kind as to point out why they're appearing out of order?
class ProfileCell: UITableViewCell {
#IBOutlet weak var historyAlbum: UIImageView!
}
class ProfileViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var historyAlbums = [PFFile]()
var albumCovers = [UIImage]()
// An observer that reloads the tableView
var imageSet:Bool = false {
didSet {
if imageSet {
// Reload tableView on main thread
dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) { // 1
dispatch_async(dispatch_get_main_queue()) { // 2
self.tableView.reloadData() // 3
}
}
}
}
}
// An observer for when each image has been downloaded and appended to the albumCovers array. This then calls the imageSet observer to reload tableView.
var dataLoaded:Bool = false {
didSet {
if dataLoaded {
let albumArt = historyAlbums.last!
albumArt.getDataInBackgroundWithBlock({ (imageData, error) -> Void in
if error == nil {
if let imageData = imageData {
let image = UIImage(data: imageData)
self.albumCovers.append(image!)
}
} else {
println(error)
}
self.imageSet = true
})
}
self.imageSet = false
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Queries Parse for each image
var query = PFQuery(className: "Songs")
query.whereKey("user", equalTo: PFUser.currentUser()!.email!)
query.orderByDescending("listenTime")
query.limit = 20
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if error == nil {
if let objects = objects as? [PFObject] {
for object in objects {
if let albumCover = object["albumCover"] as? PFFile {
// Appending each image to albumCover array to convert from PFFile to UIImage
self.historyAlbums.append(albumCover)
}
self.dataLoaded = true
}
}
} else {
println(error)
}
self.dataLoaded = false
})
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var profileCell = tableView.dequeueReusableCellWithIdentifier("ProfileCell", forIndexPath: indexPath) as! ProfileCell
profileCell.historyAlbum.image = albumCovers[indexPath.row]
return profileCell
}
}
}
The reason you are getting them out of order is that you are firing off background tasks for each one individually.
You get the list of objects all at once in a background thread. That is perfectly fine. Then once you have that you call a method (via didset) to iterate through that list and individually get each in their own background thread. Once each individual thread is finished it adds it's result to the table array. You have no control on when those background threads finish.
I believe parse has a synchronous get method. I'm not sure of the syntax currently. Another option is to see if you can "include" the image file bytes with the initial request, which would make the whole call a single background call.
Another option (probably the best one) is to have another piece of data (a dictionary or the like) that marks a position to each of your image file requests. Then when the individual background gets are finished you know the position that that image is supposed to go to in the final array. Place the downloaded image in the array at the location that the dictionary you created tells you to.
That should solve your asynchronous problems.
I'm having a rather common issue, but the solutions so far have not given me the desired result.
I have a UITableView that I am populating with information that I have parsed from a JSON pulled from the web at run time. The JSON retrieval starts in func viewDidLoad() using the NSURLSession.dataTaskWithURL(NSURL, completionHandler) function. The cells of the table are then populated within the completionHandler.
The cells used in the table are custom, and all UI elements in the cell have default values set through the interface builder.
When the table appears it is completely empty, though it does have the proper cell height. The reason I found for this behavior is that the reloadData function isn't being called at the right time due to multithreading/multiprocessing and the suggested solution is to have
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
somewhere in the code to allow the reload to occur correctly. However, this only partially works. The table flickers with what looks like content, and then immediately goes blank again until I scroll. Once I scroll the reloadData function works as expected, but only after I scroll.
I've tried having the reloadData function in various locations (such as in viewWillAppear) with no luck. Are there any ideas or troubleshooting tips that I can try?
Edit #1 - Request for completion handler
var listTask = session.dataTaskWithURL(listUrl, completionHandler: {(data, response, error) in
if error == nil {
var json:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary
var topGames = json["top"] as [NSDictionary]
var currGame:NSDictionary
var toAdd:Game
for var i=0; i < topGames.count; ++i {
currGame = topGames[i]["game"] as NSDictionary
toAdd = Game(
id: String(currGame["_id"] as CLong),
name: currGame["name"] as NSString,
boxArtImageUrl: (currGame["box"] as NSDictionary)["medium"] as NSString,
boxArtImage: nil,
isFetchingBoxArt: false,
totalViewers: topGames[i]["viewers"] as Int,
totalChannels: topGames[i]["channels"] as Int,
topChannel: "N/A")
self.games.append(toAdd)
}
dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})
}
}
Note that the self.games array is used in func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCel to fill in the information in the cells.
Edit #2 - Request for cellForRowAtIndexPath
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:TopGameListCell = self.tableView.dequeueReusableCellWithIdentifier("topGameCell") as TopGameListCell
if games.count > 0 {
var game:Game = games[indexPath.row]
cell.nameLabel?.text = game.name
cell.totalViewersLabel.text = String(game.totalViewers)
cell.totalChannelsLabel.text = String(game.totalChannels)
cell.topChannelLabel.text = game.topChannel
if game.boxArtImage != nil {
cell.boxArtImageView.image = game.boxArtImage
} else {
if(!game.isFetchingBoxArt) {
cell.boxArtImageView.image = placeholderImage
gatherGameBoxArtImageForCell(game.boxArtImageUrl, indexPath: indexPath)
}
}
}
return cell;
}
I forgot about the extra fetch that I start within the gatherGameBoxArtImageForCell. Basically if I don't already have the image, download it. The if/else for the image seems to be causing the flicker to occur. If I let it sit long enough, it finally shows the table. The idea for me is that the placeholder image would show until the image is downloaded, and then reloadData is called after the image is downloaded. Here is the image fetch completionHandler:
var task = session.dataTaskWithURL(url, completionHandler: {(data, response, error) in
var game = self.games[indexPath.row]
if error == nil {
if(game.boxArtImage == nil) {
var cellForImage:TopGameListCell? = self.tableView.cellForRowAtIndexPath(indexPath) as? TopGameListCell
if cellForImage != nil {
self.games[indexPath.row].boxArtImage = UIImage(data: data)
cellForImage?.boxArtImageView.image = self.games[indexPath.row].boxArtImage
}
}
} else {
println(error)
}
game.isFetchingBoxArt = false
self.tableView.reloadData()
})
It appears that when I was trying to have the images load in the background it was hogging up the main thread. What I did was changed the following from
if(!game.isFetchingBoxArt) {
cell.boxArtImageView.image = placeholderImage
gatherGameBoxArtImageForCell(game.boxArtImageUrl, indexPath: indexPath)
}
to
if(!game.isFetchingBoxArt) {
cell.boxArtImageView.image = placeholderImage
dispatch_async(dispatch_get_main_queue(), {
self.gatherGameBoxArtImageForCell(game.boxArtImageUrl, indexPath: indexPath)
})
}
I decided to do this after thinking on how the normal solution is to place reloadData in a dispatch_async. Apparently the reasoning is the same for the issue I was having, so now the download of the images runs asynchronously.
I am using parse to store and retrieve some data, which I then load into a UITableview, each cell contains some text and image, however when I open my tableview, any cells in the view do not show images until I scroll them out of view and back into view (I guess this is calling cellForRowAtIndexPath). Is there a way to check when all images are downloaded and then reload the tableview?
func loadData(){
self.data.removeAllObjects()
var query = PFQuery(className:"Tanks")
query.orderByAscending("createdAt")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if error == nil {
// The find succeeded.
for object in objects {
self.data.addObject(object)
}
} else {
// Log details of the failure
NSLog("Error: %# %#", error, error.userInfo!)
}
self.tableView.reloadData()
}
}
override func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell {
self.cell = tableView!.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath!) as TankTableViewCell // let cell:TankTableViewCell
let item:PFObject = self.data.objectAtIndex(indexPath!.row) as PFObject
self.cell.productName.alpha = 1.0
self.cell.companyName.alpha = 1.0
self.cell.reviewTv.alpha = 1.0
self.rating = item.objectForKey("rating") as NSNumber
cell.productName.text = item.objectForKey("prodName") as? String
cell.companyName.text = item.objectForKey("compName") as? String
self.cell.reviewTv.text = item.objectForKey("review") as? String
let userImageFile = item.objectForKey("image") as PFFile
userImageFile.getDataInBackgroundWithBlock({
(imageData: NSData!, error: NSError!) -> Void in
if (error == nil) {
let image = UIImage(data:imageData)
self.cell.productImage.image = image
}
}, progressBlock: {
(percentDone: CInt) -> Void in
if percentDone == 100{
}
})
self.setStars(self.rating)
// Configure the cell...
UIView.animateWithDuration(0.5, animations: {
self.cell.productName.alpha = 1.0
self.cell.companyName.alpha = 1.0
self.cell.reviewTv.alpha = 1.0
self.cell.reviewTv.scrollRangeToVisible(0)
})
return cell
}
The problem is that you use self.cell and that you change that reference each time a cell is returned. So, when the images are loaded they are all set into the last cell to be returned, which probably isn't on screen (or at least not fully).
Really you should be capturing the cell in the completion block of the image download (and checking that the cell is still linked to the same index path).
Also, you should cache the downloaded images so you don't always download the data / recreate the image.
You could set up a delegate method in your UITableViewController that gets called by another controller class that fetches the images. I doubt that's what you want to do though.
What you should do is initialize the cells with a default image, and have the cell controller itself go and fetch the image in the background, and update its UIImageView when the fetch completes. You definitely don't want to wait around for all images to load before reloading the table because a.) that takes a long time, and b.) what if one fails or times out?
Once the cell has loaded its image, if it is swapped out by the recycler and swapped back in, you can simply get the cached image by calling getData instead of getDataInBackground as long as isDataAvailable is true.
After your line:
self.cell.productImage.image = image
Try Adding:
cell.layoutSubviews() or self.cell.layoutSubviews()
It should render the subview, or your image in this case, on the first table view.
I am running this code for creating a tableview based on a parse query. It works, problem is I get the following error:
2014-09-24 01:09:32.187 inventario[253:20065] Warning: A long-running Parse operation is being executed on the main thread. Break on warnParseOperationOnMainThread() to debug.
I get this when using "var datta = image?.getData()" for getting the image in place. Any ideas?
{
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ModeloEquipoInventarioCell", forIndexPath: indexPath) as UITableViewCell;
let sweet:PFObject = self.timelineData.objectAtIndex(indexPath.row) as PFObject
cell.textLabel?.text = sweet.objectForKey("Modelo") as? String
cell.detailTextLabel?.text = sweet.objectForKey("Marca") as? String
// This part is the problem
var image = sweet.objectForKey("Foto3") as? PFFile
var datta = image?.getData()
cell.imageView?.image = UIImage(data: datta!)
cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
return cell
}
The method for the query was:
{
#IBAction func loadData(){
var findTimelineData:PFQuery = PFQuery(className: "InventarioListado")
findTimelineData.whereKey("Categoria", equalTo: toPassInventario)
findTimelineData.whereKey("Descripcion", equalTo: toPassModeloEquipoInventario)
//findTimelineData.orderByAscending("Descripcion")
findTimelineData.limit = 500
findTimelineData.findObjectsInBackgroundWithBlock{
(objects:[AnyObject]!, error:NSError!)->Void in
if error == nil{
for object in objects{
let sweet:PFObject = object as PFObject
let sweeter:NSString! = sweet.objectForKey("Modelo") as? NSString
var filtro = self.categoriasFiltradasDeInventario.containsObject(sweeter!)
if (filtro == false) {
self.categoriasFiltradasDeInventario.addObject(sweeter)
self.timelineData.addObject(sweet)
}
self.tableView.reloadData()
}
}
}
}
}
The problem is that the getData() function loads data via network connection and it can take some time to download an image. Your main thread would be blocked during this time so it's highly recommended to run it in the background. You can use getDataInBackgroundWithBlock() to do that easily.
let image = sweet["Foto3"] as PFFile
image.getDataInBackgroundWithBlock {
(imageData: NSData!, error: NSError!) -> Void in
if error == nil {
cell.imageView?.image = UIImage(data:imageData)
}
}
There is a basic concept in programming, Run the UI code on UI thread and Non-UI code in Non-UI thread.
Running the CPU intensive code like Network calls, I/O calls etc should be on Non-UIthread/Background thread.
Parse query to fetch image is a network call that is to be made on a background thread so the UI don't get strucked.
Use shared NSOperationQueue to shoot the query.