Show indicator while saving Swift core data

I have a button to save image data to main data, but when I click it, it freezes because the data size is large. I tried using dispatch_async but it didn't work. How do I create an icon / indicator showing that it is loading / bookmarking and not 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
        }
    }

      

+3


source to share


1 answer


First, it is unlikely that this is a slow save. I suspect your JPEG image creation is the slow part.

Second, you want to hide the problem by placing a counter. This is really bad for the user. It's much better to do the following (yes, that's more code);



  • Bring the creation and saving of the image to the background.
  • Rebuild your Core Data stack so that your files are saved to disk in a private queue.

This assumes using a background queue and multiple contexts in Core Data, but getting this data processing from the UI thread is the correct answer.

+1


source







All Articles