title: Saving/Syncing CoreData to iCloud in Swift
body: <p>Im having trouble syncing my CoreData to iCloud I Keep Getting an error in the console saying 
  <code>2015-02-22 23:09:31.229 Newstron[1711:233218] -[PFUbiquitySetupAssistant finishSetupWithRetry:](826): CoreData: Ubiquity:  &lt;PFUbiquitySetupAssistant: 0x7fbc6357e580&gt;: Retrying after delay: 60
  Error Domain=NSCocoaErrorDomain Code=134080 "The operation couldn’t be completed. (Cocoa error 134080.)" UserInfo=0x7fbc637794f0 {Reason=Didn't get a container URL back from URLForUbiquityContainerIdentifier:, giving up now. Please ensure the application is signed with the proper entitlements to read from the container., NSPersistentStoreUbiquitousContainerIdentifierKey=null}</code></p>
  
  <p>Ive Got code in AppDelegate.swift</p>
  
  <pre><code>// MARK: - Core Data stack
  func observeCloudActions(persistentStoreCoordinator psc: NSPersistentStoreCoordinator?) {
      // iCloud notification subscriptions
      let nc = NSNotificationCenter.defaultCenter();
      nc.addObserver(
          self,
          selector: "storesWillChange:",
          name: NSPersistentStoreCoordinatorStoresWillChangeNotification,
          object: psc);
  
      nc.addObserver(
          self,
          selector: "storesDidChange:",
          name: NSPersistentStoreCoordinatorStoresDidChangeNotification,
          object: psc);
  
      nc.addObserver(
          self,
          selector: "persistentStoreDidImportUbiquitousContentChanges:",
          name: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
          object: psc);
  
      nc.addObserver(
          self,
          selector: "mergeChanges:",
          name: NSManagedObjectContextDidSaveNotification,
          object: psc);
  }
  
  func mergeChanges(notification: NSNotification) {
      NSLog("mergeChanges notif:\(notification)")
      if let moc = managedObjectContext {
          moc.performBlock {
              moc.mergeChangesFromContextDidSaveNotification(notification)
              self.postRefetchDatabaseNotification()
          }
      }
  }
  
  func persistentStoreDidImportUbiquitousContentChanges(notification: NSNotification) {
      self.mergeChanges(notification);
  }
  
  // Subscribe to NSPersistentStoreCoordinatorStoresWillChangeNotification
  // most likely to be called if the user enables / disables iCloud
  // (either globally, or just for your app) or if the user changes
  // iCloud accounts.
  func storesWillChange(notification: NSNotification) {
      NSLog("storesWillChange notif:\(notification)");
      if let moc = self.managedObjectContext {
          moc.performBlockAndWait {
              var error: NSError? = nil;
              if moc.hasChanges &amp;&amp; !moc.save(&amp;error) {
                  NSLog("Save error: \(error)");
              } else {
                  // drop any managed objects
              }
  
              // Reset context anyway, as suggested by Apple Support
              // The reason is that when storesWillChange notification occurs, Core Data is going to switch the stores. During and after that switch (happening in background), your currently fetched objects will become invalid.
  
              moc.reset();
          }
  
          // now reset your UI to be prepared for a totally different
          // set of data (eg, popToRootViewControllerAnimated:)
          // BUT don't load any new data yet.
      }
  }
  
  // Subscribe to NSPersistentStoreCoordinatorStoresDidChangeNotification
  func storesDidChange(notification: NSNotification) {
      // here is when you can refresh your UI and
      // load new data from the new store
      NSLog("storesDidChange posting notif");
      self.postRefetchDatabaseNotification();
  }
  
  func postRefetchDatabaseNotification() {
      dispatch_async(dispatch_get_main_queue(), { () -&gt; Void in
          NSNotificationCenter.defaultCenter().postNotificationName(
              "kRefetchDatabaseNotification", // Replace with your constant of the refetch name, and add observer in the proper place - e.g. RootViewController
              object: nil);
      })
  }
  
  lazy var applicationDocumentsDirectory: NSURL = {
      // The directory the application uses to store the Core Data store file. This code uses a directory named "hyouuu.pendo" in the application's documents Application Support directory.
      let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
      return urls[urls.count-1] as! NSURL
      }()
  
  lazy var managedObjectModel: NSManagedObjectModel = {
      // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
      let modelURL = NSBundle.mainBundle().URLForResource("MyAppData", withExtension: "momd")!
      NSLog("modelURL:\(modelURL)")
      return NSManagedObjectModel(contentsOfURL: modelURL)!
      }()
  
  lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
      // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
      // Create the coordinator and store
      var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
      let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MyAppData.sqlite")
      NSLog("storeURL:\(url)")
      var error: NSError? = nil
      var failureReason = "There was an error creating or loading the application's saved data."
      if coordinator!.addPersistentStoreWithType(
          NSSQLiteStoreType,
          configuration: nil,
          URL: url,
          options: [NSPersistentStoreUbiquitousContentNameKey : "MyAppName"],
          error: &amp;error) == nil
      {
          coordinator = nil
          // Report any error we got.
          let dict = NSMutableDictionary()
          dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
          dict[NSLocalizedFailureReasonErrorKey] = failureReason
          dict[NSUnderlyingErrorKey] = error
          //error = NSError(domain: "Pendo_Error_Domain", code: 9999, userInfo: dict as! [NSObject : AnyObject])
          // Replace this with code to handle the error appropriately.
          // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
          NSLog("AddPersistentStore error \(error), \(error!.userInfo)")
      }
  
      self.observeCloudActions(persistentStoreCoordinator: coordinator)
  
      return coordinator
      }()
  
  lazy var managedObjectContext: NSManagedObjectContext? = {
      // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
      let coordinator = self.persistentStoreCoordinator
      if coordinator == nil {
          return nil
      }
      var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
      managedObjectContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
      managedObjectContext.persistentStoreCoordinator = coordinator
      return managedObjectContext
      }()
  
  // MARK: - Core Data Saving support
  
  func saveContext () {
      if let moc = self.managedObjectContext {
          var error: NSError? = nil
          if moc.hasChanges &amp;&amp; !moc.save(&amp;error) {
              // Replace this implementation with code to handle the error appropriately.
              // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
              NSLog("Unresolved error \(error), \(error!.userInfo)")
          }
      }
  }
  </code></pre>
  
  <p>I don't know what the problem is the Code Signing looks to be ok all correct but I keep getting this error I've looked on Apple Developer Forms no answers, Looked on overflow and google same no Answers to my problem. theres not that much documentation on that error I'm getting. So is there a better way to implement CoreData with iCloud Integration or is there a Fix for this problem. The Code in AppDelegate.swift is the only place I Have iCloud Code implemented. </p>