Advertisement
croc

Preload into Core Data

May 31st, 2018
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.47 KB | None | 0 0
  1. private func preloadData() {
  2.         let preloadedDataKey = "didPreloadData"
  3.        
  4.         let userDefaults = UserDefaults.standard
  5.        
  6.         if userDefaults.bool(forKey: preloadedDataKey) == false {
  7.            
  8.             guard let urlPath = Bundle.main.url(forResource: "Services", withExtension: "plist", subdirectory: "Data") else {
  9.                 return
  10.             }
  11.            
  12.             print(urlPath)
  13.            
  14.             let backgroundContext = persistentContainer.newBackgroundContext()
  15.             persistentContainer.viewContext.automaticallyMergesChangesFromParent = true
  16.            
  17.             backgroundContext.perform {
  18.                 if let arrayContents = NSArray(contentsOf: urlPath) as? [Service] {
  19.                    
  20.                     do {
  21.                    
  22.                         for item in arrayContents {
  23.                             let serviceObject = Service(context: backgroundContext)
  24.                             serviceObject.name = item.name!
  25.                             serviceObject.slug = item.slug!
  26.                             serviceObject.url = item.url!
  27.                         }
  28.                        
  29.                         try backgroundContext.save()
  30.                         userDefaults.set(true, forKey: preloadedDataKey)
  31.                     } catch {
  32.                         print(error.localizedDescription)
  33.                     }
  34.                 }
  35.             }
  36.            
  37.         }
  38.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement