简体   繁体   English

如何将文件从目录复制到iPhone文档目录

[英]How to copy files from a directory to iphone document directory

What I am trying to do is, in app delegate, I want to write a code that will copy a sqlite database if it is not exists in iphone's document directory. 我想做的是,在应用程序委托中,我想编写一个代码,如果iphone的文档目录中不存在sqlite数据库,它将复制该数据库。 For that I am using the following code- 为此,我正在使用以下代码-

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let containerViewController = ContainerViewController()
window!.rootViewController = containerViewController
window!.makeKeyAndVisible()

//Create database if not exists
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] as! String
let databaseStr = "LocalDatabase.sqlite"
let dbPath = docsPath.stringByAppendingPathComponent(databaseStr)
let fileManager: NSFileManager = NSFileManager.defaultManager()
if !fileManager.fileExistsAtPath(dbPath) {
    let databaseInApp: String? = NSBundle.mainBundle().resourcePath?.stringByAppendingPathComponent(databaseStr)
    fileManager.copyItemAtPath(databaseInApp!, toPath: dbPath, error: nil)
}

return true
}

It's creating the database in the directory that is ok. 它在确定的目录中创建数据库。 But I am not getting ant tables there in database. 但是我没有在数据库中找到蚂蚁表。 That means new file is created instead of copying. 这意味着将创建新文件,而不是复制文件。 I am sure there are 9 tables in that database which I want to copy. 我确定该数据库中有9个表要复制。

Structure of files are as given in the screenshot- 文件的结构如屏幕截图所示-

在此处输入图片说明

Where I am wrong that I did not understand. 我错了,我不明白。 Please tell me if anybody is able to catch the problem. 请告诉我是否有人能够解决问题。 One more thing When I was running the application in the simulator with the /Users/Adelantelabs/Documents/Sidemenu.swift/SlideOutNavigation/Localdatabase.sqlite Then it was working perfectly but did not work in iphone when I run it. 还有一件事,当我使用/Users/Adelantelabs/Documents/Sidemenu.swift/SlideOutNavigation/Localdatabase.sqlite在模拟器中运行应用程序时,它运行良好,但是在我运行iphone时却无法运行。

Use this code: 使用此代码:

let fileManager = NSFileManager.defaultManager()
var error : NSError?
var doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
let destinationPath = doumentDirectoryPath.stringByAppendingPathComponent("LocalDatabase1.sqlite")
let sourcePath = NSBundle.mainBundle().pathForResource("LocalDatabase", ofType: "sqlite")
fileManager.copyItemAtPath(sourcePath!, toPath: destinationPath, error: &error)
   func copyDatabase(){

            let fileManager = NSFileManager.defaultManager()

        let dbPath = getDBPath()
        var success = fileManager.fileExistsAtPath(dbPath)


        if(!success) {
          if let defaultDBPath = NSBundle.mainBundle().pathForResource("LocalDatabase", ofType: "sqlite"){

          var error:NSError?
          success = fileManager.copyItemAtPath(defaultDBPath, toPath: dbPath, error: &error)
          println(defaultDBPath)
          if (!success){
          println("Failed to create writable database file with message\(error!.localizedDescription))")
          }
          }else{
            println("Cannot Find File In NSBundle")
          }
        }else{
          println("File Already Exist At:\(dbPath)")
        }
      }


      func getDBPath()->String
      {

      let paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
      let documentsDir = paths[0] as! String
      let databasePath = documentsDir.stringByAppendingPathComponent("LocalDatabase.sqlite")
      return databasePath;
      }

Then call it in didFinishLaunching : 然后在didFinishLaunching调用它:

  func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

     copyDatabase()
    return true
}

Swift 3.0 version Swift 3.0版本

let fileManager = FileManager.default
var doumentDirectoryPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let destinationPath = doumentDirectoryPath.appendingPathComponent("LocalDatabase.sqlite")
let sourcePath = Bundle.main.path(forResource: "LocalDatabase", ofType: "sqlite")
do{
  try fileManager.copyItem(atPath: sourcePath!, toPath: destinationPath)
}catch let error as NSError {
  print("error occurred, here are the details:\n \(error)")
}

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

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