Search code examples
iosswiftparse-platformswift3

Add unique values to my array in Parse Server (swift 3)


My Parse Server has a class called "BooksAddedByUser", which has 3 columns:

  1. objectId
  2. user - contains the username of the PFUser.current()
  3. ISBNArray - the ISBN of books added by the user

I would like to add the newly added bookNumber into the ISBNArray only if it doesn't exist in the that array yet. However, whenever I run my code below, it creates new objectIds with the same username in the class "BooksAddedByUser". And it also doesn't check if the bookNumber already exists. I'm not sure what's going on honestly.

    let booksAddedByUser = PFObject(className: "BooksAddedByUser")
    booksAddedByUser["user"] = PFUser.current()?.username

    let query = PFQuery(className: "BooksAddedByUser")
    query.whereKey("ISBNArray", contains: bookNumber)
    query.findObjectsInBackground { (objects, error) in
        if error != nil {
            print(error)
        } else {
            print(self.bookNumber)

            if let objects = objects {
                for object in objects {
                    print("book is already added i think")
                }
            }
        }
    }

booksAddedByUser.addObjects(from: [bookNumber], forKey: "ISBNArray")

booksAddedByUser.saveInBackground { (success, error) in
    if error != nil {
        print("error saving new book")
    } else {
        print("new book saved!")
    }
}

EDIT w/ new code:

    let booksAddedByUser = PFObject(className: "BooksAddedByUser")
    booksAddedByUser["user"] = PFUser.current()?.username


    let query = PFQuery(className: "BooksAddedByUser")
    query.findObjectsInBackground { (objects, error) in
        if error != nil {

            print(error)

        } else {

            print(self.bookNumber)

            if let objects = objects {

                if objects.contains(bookNumber) {

                    print("book exists")


                }

            }

        }
    }

    booksAddedByUser.addObjects(from: [bookNumber], forKey: "ISBNArray")

    booksAddedByUser.saveInBackground { (success, error) in

        if error != nil {

            print("error saving new book")

        } else {

            print("new book saved!")

        }

    }

Solution

  • You can check if an object exits in array by using this:

    if arrObjects.contains(where: { $0.bookNumberPropertyName == "bookNumber" }) {
         print("Book exists")
    }