I'm trying to retrieve the object ID of a Core Data entity.
I've two Core Data contexts: main(mainQueueConcurrency) and child(privateQueueConcurrency) - I know, it's not the best solution but I'm still learning Core Data so hopefully my next implementation will be better.
Anyways, my aim is to assign the disk location of an image download to the passed entity. Since NSURLSession works on a different thread, my main context disappears. Therefore I go with the child context.
Although since my main context is not saved when I retrieve the object ID, it's temporary and so I can't make the appropriate insertion.
I called some save statements before obtaining the object ID but it didn't made any difference.
The code below outlines my situation. I simplified some places with comments as they were irrelevant to this situation.
How can I make this happen? Thanks.
coreDataStack.managedObjectContext.performBlockAndWait{
for result in jsonCategoriesArray {
if let category = NSEntityDescription.insertNewObjectForEntityForName("Category", inManagedObjectContext: coreDataStack.managedObjectContext) as? Category {
self.insertCategory(category, usingJSON: result, withDeletionFlag: false)
}
}
}
private func insertCategory(category: Category, usingJSON json: JSON, withDeletionFlag deletionFlag: Bool) {
// Assign the text data from JSON into the entity
do {
print("Temporary Object ID: \(category.objectID.temporaryID)")
print("Object ID: \(category.objectID)")
let managedObject = try coreDataStack.managedObjectContext.existingObjectWithID(category.objectID) as? Category
} catch {
print(error)
}
// retrieve the image URL
let privateManagedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
privateManagedObjectContext.parentContext = coreDataStack.managedObjectContext
privateManagedObjectContext.performBlock {
NSURLSession.sharedSession().dataTaskWithURL(categoryIconURL) { (data, response, error) in
guard let httpUrlResponse = response as? NSHTTPURLResponse where httpUrlResponse.statusCode == 200,
let mimeType = response?.MIMEType where mimeType.hasPrefix("image"),
let data = data
where error == nil
else {
print("ERROR: Problem downloading the category icon.")
print(error)
return
}
// determine where to save the images
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String
// retrieve the image name from the image address
let iconName = categoryIconAddress.componentsSeparatedByString("/").last!
// prepare the path for the image to be saved
let iconSaveDestinationPath = documentsPath.stringByAppendingString("/" + iconName)
// write the image to the prepared path
do {
try UIImageJPEGRepresentation(UIImage(data: data)!, 1.0)?.writeToFile(iconSaveDestinationPath, options: .DataWritingAtomic)
} catch {
print("There was a problem writing the downloaded image to the disk.")
print(error)
}
managedObject?.icon = iconSaveDestinationPath
}.resume()
if privateManagedObjectContext.hasChanges {
do {
try privateManagedObjectContext.save()
} catch {
print("An error occured while saving the child context: \(error)")
}
}
coreDataStack.saveContext()
}
}