Search code examples
swiftxcodeparse-platform

Is it possible to create an Array of specific Objects in Parse?


I have made a QR scanner App, I have manually put some QR codes into parse for it to recognise, any QR codes scanned that I haven't put into parse don't get recognised.

The only thing to tell them apart is their (Info) i.e "restaurant", "nail salon" etc.

I am after a way to be able to record an Integer of how many times the chosen QRCode has been scanned, to then place on a label in the app.

I can (.count) ALL of the qrCodes saved and scanned by the user but can't seem to figure out how I can then either put all "Nail Salons" into their own array on parse or run a For loop matching the ones I need.

 // The code below will retrieve everything in the "info" column and print it to console
 // This prints "Nails Salon" x 5, "Restaurant" x3 and "Coffee Shop" x 7 in the order that they were scanned (Unorganised)
 // What block of code could I make to display what PFuser.current currently has in their parse?
 // E.g. PFUser has scanned "Nail Salon" 5 Times, "Restaurant" 3 time etc etc

    let infoCheck = PFQuery(className: "UserQRCodes")
    infoCheck.whereKey("info", contains: "")
    infoCheck.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
        if let error = error {

            print(error.localizedDescription)
        } else if let objects = objects {

            print(objects)
        }

    }

// To retrieve everything the USER has scanned and display it as String on the APP


let query = PFQuery(className: "UserQRCodes")
    query.whereKey("userName", equalTo: PFUser.current()!)
    query.findObjectsInBackground { (objects: [PFObject]?, error: Error?) in
        if let error = error {
            //log details of the failure
            print(error.localizedDescription)
        } else if let objects = objects {
            let stampees: Int = objects.count

            let totalStampees = String(stampees)
            self.stampeesCollectedLabel.text = totalStampees
            print(objects.count)
        }

    }


    // Do any additional setup after loading the view.
}

Solution

  • You want to filter elements in your array of scans. For each code type, call something like

    // '$0' is your PFObject. Replace 'name' with whatever `PFObject` property 
    // represents the object's type
    let nailSalons = objects.filter { $0.name == "Nail Salon" }
    

    You can then use this filtered array to get your count.

    Note that the filter { $0... } syntax is a shorthand for

    objects.filter { (object) throws -> Bool) in
        return object.name == "Nail Salon"
    }
    

    You'll need to use the full version if your condition is anything more complicated than a simple one-line expression. Note that in the short version, the return is implied.