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

时间:2015-08-24 05:37:25

标签: ios iphone swift sqlite

我想要做的是,在app委托中,我想编写一个代码,如果它不存在于iphone的文档目录中,将复制sqlite数据库。为此,我使用以下代码 -

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
}

它正在目录中创建数据库即可。但是我没有在数据库中获得ant表。这意味着创建新文件而不是复制。我确信该数据库中有9个表要复制。

文件结构如屏幕截图所示 -

enter image description here

我错了,我不理解。请告诉我是否有人能够发现问题。当我在模拟器中运行应用程序时,还有一件事 /Users/Adelantelabs/Documents/Sidemenu.swift/SlideOutNavigation/Localdatabase.sqlite 然后它运行得很好,但是当我运行时它在iphone中不起作用。

3 个答案:

答案 0 :(得分:3)

使用此代码:

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)

答案 1 :(得分:2)

   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;
      }

然后在didFinishLaunching中调用它:

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

     copyDatabase()
    return true
}

答案 2 :(得分:1)

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