简体   繁体   中英

How to query an PFFile By Creation Date

I am using this code to retrieve images from Parse data...

if let userPicture = object.valueForKey("Image") as? PFFile {
      userPicture.getDataInBackgroundWithBlock({ (imageData: NSData?, error: NSError?) -> Void in
           if (error == nil) {
                let image = UIImage(data:imageData!)
                self.ImageArray.insert(image!, atIndex: 0)
           }
           else {
                self.alert("Error: \(error!) \(error!.userInfo!)", Message: "Make sure you have a secure internet connection")
           }
           dispatch_async(dispatch_get_main_queue()) {
                println("Finished Pictures")
           }
      })
 }

And I am using this code to retrieve String from Parse:

 var stuffarray = [String]()

 var query = PFQuery(className:"ClassName")
 query.findObjectsInBackgroundWithBlock {
            (objects: [AnyObject]?, error: NSError?) -> Void in

      if error == nil {
           // The find succeeded.
           println("Successfully retrieved \(objects!.count) scores.")
           // Do something with the found objects
           if let objects = objects as? [PFObject] {
                for object in objects {
                     stuffarray.append(object.valueForKey("Column")! as! String)
                }
           } else {
                // Log details of the failure
                println("Error: \(error!) \(error!.userInfo!)")
           }

           dispatch_async(dispatch_get_main_queue()) {
                self.alert("\(stuffarray)", Message: "")
           }
      }
 }     

I know how to query the second example by adding the following code:

query.orderByAscending("createdAt")

My Question is, how do I query the first example(image) the same way I did it in the second example? I tried using the following code, but I get an error:

userPicture.orderByAscending("createdAt")

I tried using the following code, the text is being returned correctly, but the images are still returned in a random order...

var query = PFQuery(className:"Featured")
query.orderByDescending("createdAt")
query.findObjectsInBackgroundWithBlock {
    (objects: [AnyObject]?, error: NSError?) -> Void in

    if error == nil {
        // The find succeeded.
        println("Successfully retrieved \(objects!.count) Items.")
        // Do something with the found objects
        if let objects = objects as? [PFObject] {
            for object in objects {

                self.NameArray.insert(object.valueForKey("Text")! as! String, atIndex: 0)
                self.ItemNameArray.insert(object.valueForKey("ItemName")! as! String, atIndex: 0)


                let userImageFile = object["Image"] as! PFFile
                userImageFile.getDataInBackgroundWithBlock {
                    (imageData: NSData?, error: NSError?) -> Void in
                    if error == nil {
                        if let imageData = imageData {
                            let image = UIImage(data:imageData)

                            self.imageArray.insert(image!, atIndex: 0)
                        }
                    }



                    dispatch_async(dispatch_get_main_queue()) {

                        self.loading.hidden = true

                        self.collectionView.reloadData()

                    }

                }




            }


        }
    } else {
        // Log details of the failure
        println("Error: \(error!) \(error!.userInfo!)")

    }

        }

The reason why you get an error with the first query is because you are not fetching an array of objects. You are getting the data contents of a single PFFile which cannot be "ordered". If you are wishing to query a list of PFFiles and order them by the created date, you will need to query the Class objects that the images are attached to and then fetch the image data for each (preferably asynchronously). See the code snippet below for an example:

PFQuery *query = [PFQuery queryWithClassName:@"Photo"];
[query orderByDescending:@"createdAt"];

[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

    if (!error) {
        for (PFObject *object in objects) {

            [objectIDArray addObject:object.objectId];
            NSString *postedBy = object[@"postedBy"];
            [postedByFeedArray addObject:postedBy];
            NSString *caption = object[@"caption"];
            [captionFeedArray addObject:caption];

            PFFile *file = object[@"photoFile"];
            [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
                if (!error) {
                    [photoFeedArray addObject:data];
                }
                dispatch_async(dispatch_get_main_queue(), ^{
                    [_activityIndicator stopAnimating];
                    [_tableView reloadData];
                });
            }];

        }
    } else {
        NSLog(@"ERROR: %@", error);
    }
}];

If you need help converting that to Swift, let me know.

In response to, "I changed it to 'append', and the arrays images are still in a random order. the 2 other string items work perfectly. Why is it just the images. Please give an answer in swift.":

The reason why your images are still in a random order is because they are downloading asynchronously from the server. The PFFile getDataInBackgroundWithBlock runs in the background and smaller files may complete faster than larger files that may have started earlier.

You should not be downloading your images until you are actually ready to display them in your UICollectionView or UITableView. When you render the cell, you will call PFFile getDataInBackgroundWithBlock then and only then.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM