Search code examples
swiftcore-dataxcode6dispatch-async

Show indicator when save core data Swift


I have a button to save picture data in core data but when I push it, it is freezing because size of the data is big. I did try to use dispatch_async but it didn’t work. How do I create the icon/indicator showing that it is loading/bookmarking rather than just freezing?

      @IBAction func save() {

    let content = self.foodMenu?["content"].string
    let urlString = self.foodMenu?["thumbnail_images"]["full"]["url"]
    let urlshare = NSURL(string: urlString!.stringValue)
    let imageData = NSData(contentsOfURL: urlshare!)
    let images = UIImage(data: imageData!)    


     dispatch_async(dispatch_get_main_queue(), {


    if let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext {


        self.foodClass = NSEntityDescription.insertNewObjectForEntityForName("Foods",
            inManagedObjectContext: managedObjectContext) as! Foods

        self.foodClass.content = content
        self.foodClass.image = UIImageJPEGRepresentation(images, 1)


        var e: NSError?
        if managedObjectContext.save(&e) != true {
            println("insert error: \(e!.localizedDescription)")
            return
        }
    }

Solution

  • First, it is unlikely it is the save that is slow. I would suspect that your creation of the JPEG representation is the slow part.

    Second, you are wanting to hide a problem by putting up a spinner. That really is bad for the user experience. Far better to do the following (yes it is more code);

    1. Move your image creation and saving to a background queue.
    2. Restructure your Core Data stack so that your saves to disk are on a private queue.

    This involves using a background queue and multiple contexts in Core Data but getting this data processing off the User Interface thread is the right answer.