简体   繁体   English

如何按创建日期查询PFFile

[英]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: 我正在使用此代码从Parse中检索String:

 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". 您正在获取无法“排序”的单个PFFile的数据内容。 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). 如果希望查询PFFile列表并在创建日期之前对其进行排序,则需要查询图像附加到的Class对象,然后为每个对象获取图像数据(最好是异步获取)。 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. 如果您需要帮助将其转换为Swift,请告诉我。

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.": 作为回应,“我将其更改为'append',并且数组图像仍然是随机顺序。其他两个字符串项可以正常工作。为什么只是图像。请尽快给出答案。”:

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. PFFile getDataInBackgroundWithBlock在后台运行,并且较小的文件可能比较早启动的较大的文件完成得更快。

You should not be downloading your images until you are actually ready to display them in your UICollectionView or UITableView. 在实际准备好在UICollectionView或UITableView中显示图像之前,不应该下载图像。 When you render the cell, you will call PFFile getDataInBackgroundWithBlock then and only then. 渲染单元格时,您将仅然后再调用PFFile getDataInBackgroundWithBlock

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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