3

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
        }
    }
user2952122
  • 75
  • 1
  • 6
  • 1
    The reason the app still freezes when you attempt to dispatch it on a separate thread, is because you are putting it on the main thread. You should really be doing this to dispatch it on a separate thread so the app doesn't freeze. dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)) – Aaron Jul 16 '15 at 05:00
  • To show an activity indicator you need to put one in your view, create an IBOultet and when you want it to appear just call activityIndicator.startAnimating() to animate and activityIndicator.stopAnimating() to stop it. – brduca Jul 16 '15 at 09:20

1 Answers1

1

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.

Marcus S. Zarra
  • 46,571
  • 9
  • 101
  • 182