I have a 8000 by 10 spreadsheet in Excel that I am building an iOS app around. I want to be able to access the data in each cell, be able to search for data in cells, and get access to related data by row.
However, I am having trouble preloading the spreadsheet to Core Data. I see a lot of different implementations online with different spreadsheet file types (.xlsx, .csv, .plist, .sqlite, etc.) but they all seem very outdated (usually in Swift 3) and I can't seem to make any of the code work in Swift 5 and xCode 11. I've been mostly experimenting with preloading data with an existing SQLite database shown below from here but cannot get it to work with Swift 5 (Tutorial is from 2015).
Are there any updated resources for preloading spreadsheet data to Core Data in Swift 5? Any recommendations for file type for the spreadsheet? Would appreciate any advice, thank you!
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// let defaults = UserDefaults.standard
// let isPreloaded = defaults.bool(forKey: "isPreloaded")
// if !isPreloaded {
// preloadData()
// defaults.set(true, forKey: "isPreloaded")
// }
//
// return true
preloadData()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func parseCSV (contentsOfURL: NSURL, encoding: String.Encoding, error: NSErrorPointer) -> [(name:String, detail:String, price: String)]? {
// Load the CSV file and parse it
let delimiter = ","
var items:[(name:String, detail:String, price: String)]?
do {
let content = try String(contentsOf: contentsOfURL as URL)
items = []
let lines:[String] = content.components(separatedBy: NSCharacterSet.newlines) as [String]
for line in lines {
var values:[String] = []
if line != "" {
// For a line with double quotes
// we use NSScanner to perform the parsing
if line.range(of: "\"") != nil {
var textToScan:String = line
var value:NSString?
var textScanner:Scanner = Scanner(string: textToScan)
while textScanner.string != "" {
if (textScanner.string as NSString).substring(to: 1) == "\"" {
textScanner.scanLocation += 1
textScanner.scanUpTo("\"", into: &value)
textScanner.scanLocation += 1
} else {
textScanner.scanUpTo(delimiter, into: &value)
}
// Store the value into the values array
values.append(value! as String)
// Retrieve the unscanned remainder of the string
if textScanner.scanLocation < (textScanner.string.count) {
textToScan = (textScanner.string as NSString).substring(from: textScanner.scanLocation + 1)
} else {
textToScan = ""
}
textScanner = Scanner(string: textToScan)
}
// For a line without double quotes, we can simply separate the string
// by using the delimiter (e.g. comma)
} else {
values = line.components(separatedBy: delimiter)
}
// Put the values into the tuple and add it to the items array
let item = (name: values[0], detail: values[1], price: values[2])
items?.append(item)
}
}
} catch {
print(error)
}
return items
}
func preloadData () {
// Retrieve data from the source file
if let contentsOfURL = Bundle.main.url(forResource: "menudata", withExtension: "csv") {
// Remove all the menu items before preloading
removeData()
var error:NSError?
if let items = parseCSV(contentsOfURL: contentsOfURL as NSURL, encoding: String.Encoding.utf8, error: &error) {
// Preload the menu items
if let managedObjectContext = (UIApplication.shared.delegate as? AppDelegate)?.managedObjectContext {
for item in items {
let menuItem = NSEntityDescription.insertNewObject(forEntityName: "MenuItem", into: managedObjectContext) as! MenuItem
menuItem.name = item.name
menuItem.detail = item.detail
menuItem.price = (item.price as NSString).doubleValue as NSNumber
// if managedObjectContext.save {
// print("insert error: \(error!.localizedDescription)")
// }
}
}
}
}
}
func removeData () {
// Remove the existing items
do {
let managedObjectContext = self.managedObjectContext
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "MenuItem")
let menuItems = try! managedObjectContext.fetch(fetchRequest) as! [MenuItem]
for menuItem in menuItems {
managedObjectContext.delete(menuItem)
}
}
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.appcoda.CoreDataDemo" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .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 = Bundle.main.url(forResource: "CoreDataDemo", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns 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
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("CoreDataDemo.sqlite")
// Load the existing database
if !FileManager.default.fileExists(atPath: url?.path ?? "") {
let sourceSqliteURLs = [Bundle.main.url(forResource: "CoreDataDemo", withExtension: "sqlite")!, Bundle.main.url(forResource: "CoreDataDemo", withExtension: "sqlite-wal")!, Bundle.main.url(forResource: "CoreDataDemo", withExtension: "sqlite-shm")!]
let destSqliteURLs = [self.applicationDocumentsDirectory.appendingPathComponent("CoreDataDemo.sqlite"), self.applicationDocumentsDirectory.appendingPathComponent("CoreDataDemo.sqlite-wal"), self.applicationDocumentsDirectory.appendingPathComponent("CoreDataDemo.sqlite-shm")]
for index in 0..<sourceSqliteURLs.count{
do {
try FileManager.default.copyItem(at: sourceSqliteURLs[index], to: destSqliteURLs[index]!)
} catch {
print(error)
}
}
}
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// 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("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
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
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// 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.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
Try to actually write data to CoreData and add the .sqlite to your app bundle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With