sathish kumar
sathish kumar

Reputation: 89

How to save user details while updating the iOS App?

I have two sqlite databases namely workout5.sqlite3 and custom_ios.sqlite3. I copy both the databases to user directory on installation

if !fileManager.fileExists(atPath: dbPath) {
    let fromPath: String? = Bundle.main.resourcePath?.stringByAppendingPathComponent(fileName as String)
    var error : NSError?
    do {
        try fileManager.copyItem(atPath: fromPath!, toPath: dbPath)
    } 
    catch let error1 as NSError {
        error = error1
    }

    let alert: UIAlertView = UIAlertView()
    if (error != nil) {
        alert.title = "Error Occured"
        alert.message = error?.localizedDescription
    } 
    else {
        alert.title = "Successfully Copy"
        alert.message = "Your database copy successfully"
    }
}

On Installation, I check whether the file exists or not. But each time when I update the app, the databases gets replaced. How to solve this issue?

Upvotes: 0

Views: 38

Answers (1)

Lal Krishna
Lal Krishna

Reputation: 16180

The documents directory will deleted only when the App is uninstalled. Check if readable file exist at path: isReadableFile(atPath:).

Here is sample code:

let DBNAME = "myDB.sqlite"
let yourOriginalDatabasePath = URL(fileURLWithPath: Bundle.main.resourcePath ?? "").appendingPathComponent(DBNAME)
let pathsToDocuments = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let dbPath = URL(fileURLWithPath: pathsToDocuments[0]).appendingPathComponent(DBNAME)
print("dataBasebPath: \(dbPath.absoluteString)")

let isFileExist = FileManager.default.fileExists(atPath: dbPath.absoluteString)
let isReadableFileExist = FileManager.default.isReadableFile(atPath: dbPath.absoluteString)
if !isReadableFileExist && !isFileExist {
     print("[DB] Copying DB to Documents Folder")
     do {
        try FileManager.default.copyItem(at: yourOriginalDatabasePath, to: dbPath)
     } catch {
        print("Fail to copy database from \(yourOriginalDatabasePath) to \(dbPath). Error: \(error)")
     }
}

Upvotes: 1

Related Questions