Search code examples
iosswiftcore-dataxmppframework

Core Data Error: Cannot fetch without an NSManagedObjectContext in scope


I am using XMPPFramework library in Swift which provides message history storage using Core Data. I am trying to request the archived messages from the storage using the following function:

func getChatHistory() {

    guard let context = xmppMessageStorage.mainThreadManagedObjectContext else {return}
    var entityDescription = NSEntityDescription.entity(forEntityName: "XMPPMessageArchiving_Message_CoreDataObject", in: context)
    var request = NSFetchRequest<NSFetchRequestResult>(entityName: "XMPPMessageArchiving_Message_CoreDataObject")
    request.entity = entityDescription
    do {
        var messages = try request.execute()
        print("Archived Messages: \n\(messages)")
    } catch let error {
        print("Error fetching chat history: \(error)")
    }

}

However, when I execute the function I receive the following error:

Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={message=Cannot fetch without an NSManagedObjectContext in scope}

I can't understand why this is happening as I am setting the context properly in my code. I would appreciate it if someone could help me understand what's wrong here.


Solution

  • Try to replace

    request.entity = entityDescription
    do {
      var messages = try request.execute()
      print("Archived Messages: \n\(messages)")
    } catch let error {
      print("Error fetching chat history: \(error)")
    }
    

    With

    do {
      let messages = try context.fetch(request)
      print("Archived Messages: \n\(messages)")
    } catch {
      print("Error fetching chat history:", error)
    }