Parse Query saving multiple objects - arrays

Currently trying to save objects to parse database, when i println the objects they contain the new array that i wanted inside the array field but for some reason it won't save to table been on this a while any ideas?
The array needs to add a new integer value for each one corresponding to each the queries,the "test" array archives this but saving each object to the USER class seems to be a problem
func taskAllocation(){
// var query = PFQuery(className: "Tasks")
var query = PFUser.query()
// let user = PFUser()
var posts:[PFUser] = []
query.whereKey("Year", equalTo: yearTextField.text.toInt())
query.whereKey("Class", equalTo: classTextField.text.toInt())
query.whereKey("Keystage", equalTo: keystageTextField.text.toInt())
// query.limit = 10
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
if error != nil {
println(error)
} else {
if objects.isEmpty {
println("empty query")
}
else {
for object in objects as [PFUser] {
var test:[Int] = object["taskIDs"] as [Int]
test.append(self.getIndex)
println(test)
object.setValue(test, forKey: "taskIDs")
object["tasksCorrect"] = "hello"
posts.append(object)
}
println(posts)
PFUser.saveAllInBackground(posts)
}}}

I assume you want to save these components to your "Tasks" class and not your User class. PFUser Query is just for the "_User" class which does not have the tasks in it.
var tasks:PFObject = PFObject(className: "Tasks")
// Make sure in your parse data table you have the columns created as type String or Int
item["Year"] = yearTextField.text.toInt()
item["Keystage"] = keystageTextField.text.toInt()
item["Class"] = classTextField.text.toInt())
// Save the task to a user, make sure you create a Username column in your data table
item["Username"] = PFUser.currentUser().username
// save it
item.saveInBackgroundWithTarget(nil , selector: nil)
Your code is a little clunky so I made assumptions on what your trying to do. It might be beneficial taking a screen shot of your task class.

Related

Problem on RealmSwift: "Invalid array input: more values (1) than properties (0)." while trying to persist an Array of String

I'm trying to persist in a table view cell, the result of a quiz test with questions and I needed the array of answers given (String Array) so I decided to use RealmSwift.
I created this class and of course I created also a RealmString object in the same file to handle the possibility to persist arrays of String in Realm in this way:
class RealmString: Object {
dynamic var stringValue = ""
}
class Test: Object {
#objc dynamic var ID = UUID().uuidString
#objc dynamic var testScore : String = String()
#objc dynamic var testTitle : String = String()
#objc dynamic var testSubTitle : String = String()
#objc dynamic var dateOfExecution: String = String()
#objc dynamic var answersGiven: [String] {
get {
return _backingAnswersGiven.map { $0.stringValue }
}
set {
_backingAnswersGiven.removeAll()
_backingAnswersGiven.append(objectsIn: (newValue.map({ RealmString(value: [$0]) })))
}
}
let _backingAnswersGiven = List<RealmString>()
override static func ignoredProperties() -> [String] {
return ["answersGiven"]
}
override static func primaryKey() -> String? {
return "ID"
}
Now in the view controller:
I have a variable that stores the result (is an Int array that will take ten answers with values from 0 to 5, and these will later be converted to String)
i.e.: [0,2,2,3,4,5,2,1,0,2] -> ["0","2","2","3","4","5","2","1","0","2"]
and when an option is selected in a question the value is set with this function, everything works fine.
public var questionResults: [Int] = []
func setValueToQuestion(questionNumber: Int) {
questionResults[questionNumber] = optionChosen
}
When the test is completed successfully everything is saved in this way:
let test = Test()
test.ID = currentTest?.ID ?? UUID().uuidString
test.testTitle = testTitleLabel.text!
test.testScore = resultNumberLabel.text!
test.testSubTitle = resultLabel.text!
test.dateOfExecution = dateTimeString
test.answersGiven = questionResults.map({String($0)})
DBManager.sharedInstance.addData(object: test)
I tried the code separately also adding breakpoints and everything works in the flow, expect this line:
test.answersGiven = questionResults.map({String($0)})
that raises the error shown in the title: "Invalid array input: more values (1) than properties (0)."
I guess it can be an error of mapping maybe?
This value is then treated in the rest of flow as a simple swift array of String = [String]
There are a few issues which may be leading to that error.
First the RealmString property is not persisted because it needs #objc
dynamic var stringValue = ""
should be
#objc dynamic var stringValue = ""
Secondly, and this is important, Realm does not support primitives in Lists. Well, it kinda does but not very well.
EDIT: Release 10.7 added support for filters/queries as well as aggregate functions on primitives so the below info is no longer completely valid. However, it's still something to be aware of.
See my answer to this question but in a nutshell, you need another class to store the string in - kind of like your RealmString class.
class StringClass: Object {
#objc dynamic var myString = ""
}
and then change the Test object property to use the StringClass property
#objc dynamic var answersGiven = [StringClass]()
and then I see you're trying to use a backed var and computed property but I am not sure why. It may be simpler to use use the var itself
let _backingAnswersGiven = List<RealmString>()
since the List collection already handles what's being computed.
For example, if you set the list you can set it to another list (which wipes out the current list). Or when you get the list let myStringList = test._backingAnswersGiven, gets all of the StringClasses in the list without having to .map over them.

How to order PFObjects based on its creation date?

I have some user comments stored in a database (parse-server) that I would like to would like to display on my viewController's viewDidLoad(). I can easily pull the comment objects as follows:
super.viewDidLoad()
func query(){
let commentsQuery = PFQuery(className: "Comments")
commentsQuery.whereKey("objectId", equalTo: detailDisclosureKey)
commentsQuery.findObjectsInBackground { (objectss, error) in
if let objects = objectss{
if objects.count == 1{
for object in objects{
self.unOrderedComments.append(object)
}
}
}
}
}
This query dumps all of the of the comments in the unOrederedComments array. Each comment is added to the database with a createdAt property automatically being added relating the exact time of its creation. This property is a string with (as an example) the form: "2017-08-13T19:31:47.776Z" (the Z at the end is at the end of every string... not exactly sure why its there but its constant). Now, each new comment is added in order to the top of database and thus any queried result should be in order regardless. However, I would like to make sure of this by reordering it if necessary. My general thought process is to use .sorted, but I cannot figure out how to apply this to my situation
func orderComments(unOrderComments: [PFObject]) -> [PFObject]{
let orderedEventComments = unOrderedEventComments.sorted(by: { (<#PFObject#>, <#PFObject#>) -> Bool in
//code
})
}
This is the generic set up but I cannot, despite looking up several examples online figure out what to put in the <#PFObject#>'s and in the //code. I want to order them based on the "createdAt" property but this is not achieved via dot notation and instead requires PFObject["createdAt"] and using this notation keeps leading to error. I feel as so though I may need to set up a custom predicate but I do not know how to do this.
I was in the same situation, what I did was to first create an array of structs with the data I downloaded where I turned the string createdAt into a Date, then used this function:
dataArrayOrdered = unOrderedArray.sorted(by: { $0.date.compare($1.date) == .orderedAscending})
(.date being the stored Date inside my array of strcuts)
Try this code, notice that I assumed you have a variable name called ["Comments"] inside your Parse database, so replace if necessary. Also, I realised that createdAt it's in Date format, so there was no need to change it from String to Date, chek if it works the same for you, if it doesn't refer to this: Swift convert string to date.
struct Comment {
var date = Date()
var comment = String()
}
var unOrderedComments: [Comment] = []
var orderedComments = [Comment]()
override func viewDidLoad() {
super.viewDidLoad()
query()
}
func query(){
let commentsQuery = PFQuery(className: "Comments")
commentsQuery.findObjectsInBackground { (objectss, error) in
if let objects = objectss{
if objects.count >= 1{
for object in objects{
let newElement = Comment(date: object.createdAt!, comment: object["Comments"] as! String)
self.unOrderedComments.append(newElement)
print(self.unOrderedComments)
}
}
self.orderedComments = self.unOrderedComments.sorted(by: { $0.date.compare($1.date) == .orderedAscending})
print(self.orderedComments)
}
}
}

How to retrieve objectID from within a class on parse server using swift

Alright so i'm starting to get a headache here... Once my user sign onto my app i create a new class on parse with the name PFUser.Current()?.objectId! Within this class i store all the users information, and the user can acces it from any device since his user ID never changes. One of the things i store in the user class is an array which leads me to my question: I want to be able to acces this array but the only way this can be done is by using:
var query = PFQuery(className: "\(PFUser.current()?.objectId!)") // Calling the user class
query.getObjectInBackground(withId: "") { (object: PFObject?, error: Error?) in
if error != nil {
print(error)
} else {
print(object)
}
}
The Problem is that i do not know how to retrieve the objectID from within the class UserObjectID.
I found some code that lets me retrieve my user list and append usernames and iDs to an array:
var query = PFUser.query()
query?.findObjectsInBackground { (objects, error) in
if let users = objects {
for object in users {
if let user = object as? PFUser {
self.usernames.append(user.username!)
self.userids.append(user.objectId!)
}
}
}
}
How can i do a similar search, and find all the objectIDs within my individual userClass instead of the superUser class?
Are you sure you want to create a new class for each user? you going to end up with an enormous amount of tables with 1 row in each. Best to add your array as a column in the current _User table or create a new table and save all user arrays in it with a pointer.
That being said if do and your new table is named from the objectId of the user then you should be able to query that class with:
var userId: String = ""
let userClassName = PFUser.current()!.objectId!
let query = PFQuery(className: userClassName)
// as there is only 1 row get the first
query.getFirstObjectInBackground { (object, error) in
if error != nil || object == nil {
print("nothing here try again")
} else {
userId = object?.objectId
}
}
If you have a table with many users and a pointer then use the following lines as a guide
let userObjectId = PFUser.current()!.objectId!
query.whereKey("yourPointerName", equalTo: PFObject(outDataWithClassName: "theClassYouWantToQuery", objectId: userObjectId))

In Swift, how do you execute one query to Parse before another on PFQueryTableViewController?

I am trying to do two queries to Parse in my PFQueryTableViewController. I am trying to do one query to obtain all of the objects relating to the currentUser and then place those objects into an array. After the array is filled with its objects, I would like to do another query from
override func queryForTable() -> PFQuery { }.
This second query will use the objects from the array that was created from the first query, in order to retrieve objects of its own.
I don't know how to make the first query execute before the second. As of right now, the second query will execute before the first one before it has a chance to fill the array and as a result messes up the query for the second one. The following is what i have for my code at this point.
class PFNewsFeedTableViewController: PFQueryTableViewController {
var leadersArray : NSMutableArray = NSMutableArray()
override func viewDidAppear(animated: Bool) {
leadersArray.removeAllObjects()
var findLeaders = PFQuery(className: "Follow")
findLeaders.whereKey("follower", equalTo: PFUser.currentUser()!)
findLeaders.orderByDescending("createdAt")
findLeaders.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
//If no error
if error == nil {
println("Successfully retrieved \(objects!.count) leaders.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
self.leadersArray.addObject(object.objectForKey("leader")!)
}
}
}
self.tableView.reloadData()
self.queryForTable()
}
}
override func queryForTable() -> PFQuery {
var findContent = PFQuery(className: "Content")
findContent.whereKey("user", containedIn: self.leadersArray as [AnyObject])
findContent.orderByDescending("createdAt")
return findContent
}
}
Is there a way to determine the order in which these queries get executed? Any help to this problem would be appreciated.
Yes, you can.
Let me first start by saying that it does sound like you should try to maybe rethink your data model, as executing two queries in succession like this is often a sign of focusing too much on traditional data modeling rather than the more pragmatic nosql-style of modeling where you (especially for mobile apps) should model for queries rather than normalisation.
If you were to solve your case like you said, you can employ the Bolts framework. No need to install this, as this is already installed as part of Parse (which uses Bolts behind the scenes).
It could then look something like this (just a quick write-up. Will probably not work out of the box, but you should be able to make it fit):
var findLeaders = PFQuery(className: "Follow")
findLeaders.whereKey("follower", equalTo: PFUser.currentUser()!)
findLeaders.orderByDescending("createdAt")
findLeaders.findObjectsInBackground().continueWithBlock {
(task: BFTask!) -> AnyObject! in
//If no error
if task.error != nil {
print("Something went wrong...")
} else {
// Do something with the found objects
if let objects = task.result as? [PFObject] {
print("Successfully retrieved \(objects.count) leaders.")
for object in objects {
self.leadersArray.addObject(object.objectForKey("leader")!)
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.tableView.reloadData()
})
self.queryForTable()
return nil
}
I figured out the problem and it looks like this
override func queryForTable() -> PFQuery {
var findLeaders = PFQuery(className: "Follow")
findLeaders.whereKey("follower", equalTo: PFUser.currentUser()!)
findLeaders.orderByDescending("createdAt")
var findContent = PFQuery(className: "Content")
findContent.whereKey("user", matchesKey: "leader", inQuery: findLeaders)
findContent.orderByDescending("createdAt")
return findContent
}

How to put Parse data in an array

I need to put data in the array using a query, but it only works in the block. I searched here and found out that it's because the findObjectsInBackgroundWithBlock is asynchronous, but how can I make it synchronous then?
var cities = [String]()
func loadCityArray() {
let citiesVisited = PFQuery(className: "Trips")
citiesVisited.whereKey("userId", equalTo: (PFUser.currentUser()?.objectId)!)
citiesVisited.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if let objects = objects {
for object in objects {
let city = object["cityId"] as! String
let query = PFQuery(className: "Cities")
query.whereKey("objectId", equalTo: city)
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
if let objects = objects {
for object in objects {
self.cities.append(object["cityName"] as! String)
}
}
})
}
}
You do not want to make that synchonous on the main thread. That is strongly discouraged.
You rather want to store the things you need from the request in instance variables and tell the corresponding View Controller new values are present in the block.
edit:
Suppose you have an object waiting to use the data:
var chart : DataConsumer?
In the block where you get the data,
chart.useData(data)
edit 2:
the useData function should keep track of changes in the data set and make use of the information that new data arrived. For example, by displaying it.

Resources