Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to create a connection between my program and a database located in /Documents of the app. When the code is built using on the simulator, it successfully opens the database; however, when I run the code on an iOS device, it can't find the file.

This is the code that I use:

let path = NSSearchPathForDirectoriesInDomains(
        .documentDirectory, .userDomainMask, true
    ).first!
    
    let db = try! Connection("(path)/Database.db")

These are the contents of the variable path when I run the code on the simulator:

/Users/xxxx/Library/Developer/CoreSimulator/Devices/EFD14A1B-7207-4840-9ACE-8E44A269CC70/data/Containers/Data/Application/58D150B9-E242-4857-B06C-DA28C88A26D0/Documents

And these are the contents of the variable path when I run the code on an iOS device:

/var/mobile/Containers/Data/Application/4EC93D76-4E99-4552-855A-48C1D9346449/Documents

Xcode version: 12.0
iOS device: iPhone X
iOS version: 14.1

Edit I tried to use this code to copy the database from the app bundle to the document directory, but it gives the error Unable to copy file:

copyFileToDocumentsFolder(nameForFile: "Database", extForFile: "db")


func copyFileToDocumentsFolder(nameForFile: String, extForFile: String) {

    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    let destURL = documentsURL.appendingPathComponent(nameForFile).appendingPathExtension(extForFile)
    guard let sourceURL = Bundle.main.url(forResource: nameForFile, withExtension: extForFile)
        else {
            print("Source File not found.")
            return
    }
        let fileManager = FileManager.default
        do {
            try fileManager.copyItem(at: sourceURL, to: destURL)
        } catch {
            print("Unable to copy file")
        }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
160 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can use url or path: with this codes you get the address of your data base, but you have to have your database file already there when your app use this address to find your databace! if you use this address, without having real file there, your app will crash. So if you have problem about copying your databace file let me know!

Version: 1.0.0

let appBaseURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].standardizedFileURL
let databaseURL = appBaseURL.appendingPathComponent("Database").appendingPathExtension("db").standardizedFileURL
let databasePath = databaseURL.path

Update Version: 2.0.0

This codes down are the most simplest and cleanest code about copy and paste on planet Earth for Swift and SwiftUI! You can not find better than this:

// If you want see your file in device or give user access to the file do this 2 steps:
// 1 - add this one ("Application supports iTunes file sharing" -> Yes) from (info.plist)
// 2 -add this one ("Supports opening documents in place" -> Yes) from (info.plist)
                    
let fileName = "omid"
let fileExtension = "jpeg"
                        
 let appBaseURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].standardizedFileURL
         let pasteFileURL = appBaseURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL

          let copyFileURL = Bundle.main.bundleURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL
                    
        
                    
                    if FileManager.default.fileExists(atPath: appBaseURL.path)
                    {
                        print("appBaseFolder already exists!")
                    }
                    else
                    {
                        do{ try FileManager.default.createDirectory(at: appBaseURL, withIntermediateDirectories: true, attributes: nil); print("appBaseFolder successfully created!") }
                        catch{ print("Error in creating appBaseFolder!") }
                    }
                    
        
                    
                    if      FileManager.default.fileExists(atPath: pasteFileURL.path)
                    {
                        print("The selected file already exists!")
                    }
                    else
                    {
                        do{ try FileManager.default.copyItem(at: copyFileURL, to: pasteFileURL); print("The selected file successfully copied!") }
                        catch { print("Error with copying selected file!") }
                    }

Version: 3.0.0 (The GM Version)

//▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲▲
// If you want see your file in device or give user access to the file do this 2 steps:
// 1 - add this one ("Application supports iTunes file sharing" -> Yes) from (info.plist)
// 2 - add this one ("Supports opening documents in place" -> Yes) from (info.plist)
//...........................................................
let fileName = "omid"
let fileExtension = "jpeg"
//...........................................................
let appBaseURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].standardizedFileURL
let pasteFileURL = appBaseURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL
let copyFileURL = Bundle.main.bundleURL.appendingPathComponent(fileName).appendingPathExtension(fileExtension).standardizedFileURL
//▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼▼




//...........................................................
if FileManager.default.fileExists(atPath: appBaseURL.path)
{
    print("appBaseFolder already exists!")
}
else
{
    do{ try FileManager.default.createDirectory(at: appBaseURL, withIntermediateDirectories: true, attributes: nil); print("appBaseFolder successfully created!") }
    catch{ print("Error in creating appBaseFolder!") }
}
//...........................................................



//...........................................................
if FileManager.default.fileExists(atPath: copyFileURL.path)
{
    //...........................................................
    if      FileManager.default.fileExists(atPath: pasteFileURL.path)
    {
        print("The selected file already exists!")
    }
    else
    {
        do{ try FileManager.default.copyItem(at: copyFileURL, to: pasteFileURL); print("The selected file successfully copied!") }
        catch { print("Error with copying selected file!") }
    }
    //...........................................................
}
else
{
    print("The selected file not exists for copy Action!") 
}
//...........................................................

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...