How to get the Cart items in a list?

swift
cart-items

#1

How can i get my cartItems that are in my cart and add them to an array of type CartItem?


#2

Hi Karl,

You can use Moltin.cart.list(itemsInCartID: "your cart ID"). This returns an array of CartItem from the API for you.

For example:

Moltin.cart.list(itemsInCartID: "<CART ID>") { result in
    switch result {
    case .success(let cartList):
        print(cartList.items) // This is [CartItem]
    case .failure(_): break
    }
}

Hope this helps!
Craig


#3

I should create my own cart? and hwo do i get the cart ID?


#4

The cart ID is a UUID that you store somewhere to keep track of the cart.

You can either create this yourself by using let cartID = UUID().uuidString, and then call Moltin.cart.list(itemsInCartID:) endpoint, or you could call Moltin.cart.getNew, this does essentially the same thing, but returns you a new Cart object from the API, which will have the UUID.


#5
    Moltin.cart.add(itemWithProductID: productid!, andQuantity: 1, toCartID: "reference1") { result in
        switch result {
        case .failure(let error):
            print("Failed to add product to cart \(error)")
        case .success:
            print("Successfully added product to cart")
            print(result)

}
this is my code and in toCartID i’ve put “reference1”.
So now “reference1” is my cartID?


#6

Yep! That’s exactly it. The reference can really be anything, but we recommend UUID's.


#7

Okay thank you for your patience!
one more question but out of topic.
If i want to decrease the quantity of a product in a cart i have to change through JSON or is there another way?


#8

If you have the ID of the item in the cart, you can use this method to change that quantity of that item:

You’ll need the cartItemID, quantity and cartID.


#9

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.