繁体   English   中英

如何在 Swift 5 中将电子表格数据预加载到 Core Data?

[英]How to preload spreadsheet data to Core Data in Swift 5?

我在 Excel 中有一个 8000 x 10 的电子表格,我正在围绕它构建一个 iOS 应用程序。 我希望能够访问每个单元格中的数据,能够搜索单元格中的数据,并按行访问相关数据。

但是,我无法将电子表格预加载到 Core Data。 我在网上看到了许多不同的电子表格文件类型(.xlsx、.csv、.plist、.sqlite 等)的不同实现,但它们似乎都非常过时(通常在 Swift 3 中),我似乎无法制作任何在斯威夫特5和Xcode的11.我的代码工作已经预载有从下方所示与现有的SQLite数据库的数据已经尝试大多在这里,但它不能获得与斯威夫特5(教程是从2015年)的工作。

在 Swift 5 中是否有用于将电子表格数据预加载到 Core Data 的更新资源? 对电子表格的文件类型有什么建议吗? 希望得到任何建议,谢谢!

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()
            }
        }
    }

}

尝试将数据实际写入 CoreData 并将 .sqlite 添加到您的应用程序包中。

  1. 定义您的核心数据模型。
  2. 编写代码来解析您的电子表格并将所有数据保存到 Core Data。
  3. 在模拟器上运行第 2 步中的代码
  4. 模拟器上的应用程序的数据存储在您的计算机上,找到 CoreData 使用的 .sqlite 文件。 (只需记录路径)。
  5. 将 .sqlite 文件添加到您的应用程序包
  6. 在第一次运行时,将 .sqlite 从包复制到 Documents 目录并使用它来初始化您的 NSPersistentStoreCoordinator。
  7. 像往常一样使用 CoreData。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM