Reputation: 3459
I'm in the process of making an app which creates events. The Event has a property user which saves successfully, but now I want to save an array of events to the current user. Each time an event is created I'm trying to add that event to an array (for key "Events" in the user class).
What's the best way to go about that in swift? Here's some sample code of where I save the event to parse.
The first gets the image file and passes it to the function to save the whole event...
@IBAction func saveEvent(sender: AnyObject) {
let pictureData = UIImagePNGRepresentation(eventImage.image)
let file = PFFile(name: "eventImage", data: pictureData)
file.saveInBackgroundWithBlock { (succeeded, error) -> Void in
if !(error != nil) {
self.saveEventToParse(file)
}
else if let error = error {
println("error: \(error.localizedDescription)")
}
}
}
This function saves the event
func saveEventToParse(file: PFFile) {
let event = Event(image: file, user: PFUser.currentUser()!, comment: eventDescriptionField.text, title: eventTitleField.text, date: datePicker.date)
event.saveInBackgroundWithBlock { (success, error) -> Void in
if success {
//I KNOW I NEED TO DO SOMETHING HERE THAT'S NOT THIS
event.user.relationForKey("Events")
var alertView = UIAlertView(title: "Event saved!", message: "Success", delegate: nil, cancelButtonTitle: "Okay!")
alertView.show()
}
else {
println("error: \(error?.localizedDescription)")
}
}
}
Thank you!
Upvotes: 0
Views: 724
Reputation: 2729
I think - in your particular case - that Relations are not the right choice. Actually, you really shouldn't be creating this on the User class, but instead making a Pointer to the User class on the Events class... it will be much faster (you would need to fetch the User everytime you wanted this anyways).
You would then query like this:
let query = PFQuery(className: "Events")
query.whereKey("userPointer", equalTo: PFUser.currentUser()!)
query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
if(error == nil) {
print(objects)
}
}
Upvotes: 0
Reputation: 846
in Parse, relation is usually used for "many-to-many" relationship.
In your case, I'm not sure that the statement which is "one event can belong to many user" is right or wrong. However, you can continue by using the relation like this:
let relation = event.user.relationForKey("Events")
relation.addObject(event)
event.user.saveInBackground()
More information you can refer here: https://parse.com/docs/ios/guide#relations-using-parse-relations
Upvotes: 1