0

I want to append json object I save in core data into an array, but it's not working with append. how I can append core data object into an array.

this is my array

private var videos = [Video]()

this my function to fetch an api and store the json into core data

let params = ["part": "snippet", "q": "tausiyah \(name)", "key": "AIzaSyC2mn0PTL8JmSWEthvksdJLvsnwo5Tu9BA"]

        APIServices.shared.fetchData(url: APIServices.youtubeBaseURL, params: params, of: Item.self) { (items) in
            items.forEach({ (item) in
                print(item.id.videoId)
                let privateContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
                privateContext.parent = CoreDataManager.shared.persistenceContainer.viewContext

                let video = Video(context: privateContext)
                video.title = item.snippet.title
                video.videoId = item.id.videoId

                do {
                    try privateContext.save()
                    try privateContext.parent?.save()
                    self.videos.append(video) // this is I can't append core data into my array
                } catch let saveErr {
                    print("Failed to save json data:", saveErr)
                }
            })
            DispatchQueue.main.async {
                self.collectionView.reloadData()
            }
        }
7
  • The fetch data will execute asynchronously. You need the DispatchQueue.main.async inside the fetch data closure. Commented Dec 18, 2018 at 11:15
  • @Paulw11 what do you mean? I need to add dispatch again so my append will work? Commented Dec 18, 2018 at 11:19
  • Sorry, I misread your }. What do you mean by "not working" and "I can't append...". What happens? Do you get an error message? Commented Dec 18, 2018 at 11:23
  • @Paulw11 my array is empty but it is save in core data Commented Dec 18, 2018 at 11:24
  • What do you see if you print the array.count after the append? It still looks like an asynchronous problem to me. Also show your numberOfItems(in section:) code Commented Dec 18, 2018 at 11:38

1 Answer 1

1

try this and see the result:

private var videos = [Video]() {
   didSet {
      print("AAA: \(videos.last().title)")
      DispatchQueue.main.async {
          self.collectionView.reloadData()
      }
   }
}

be sure that you have set numberOfItems & Section to you array.count

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.