"how to copy sqlite database when application is launched in ios?" Code Answer

4

you can add following methods to your appdelegate

- (void) copydatabaseifneeded {

    //using nsfilemanager we can perform many file system operations.
    nsfilemanager *filemanager = [nsfilemanager defaultmanager];
    nserror *error;

    nsstring *dbpath = [self getdbpath];
    bool success = [filemanager fileexistsatpath:dbpath];

    if(!success) {

       nsstring *defaultdbpath = [[[nsbundle mainbundle] resourcepath] stringbyappendingpathcomponent:@"database.sqlite"];
       success = [filemanager copyitematpath:defaultdbpath topath:dbpath error:&error];

       if (!success)
          nsassert1(0, @"failed to create writable database file with message '%@'.", [error localizeddescription]);
    }
}

- (nsstring *) getdbpath
{   
    //search for standard documents using nssearchpathfordirectoriesindomains
    //first param = searching the documents directory
    //second param = searching the users directory and not the system
    //expand any tildes and identify home directories.

    nsarray *paths = nssearchpathfordirectoriesindomains(nsdocumentdirectory , nsuserdomainmask, yes);
    nsstring *documentsdir = [paths objectatindex:0];
    //nslog(@"dbpath : %@",documentsdir);
    return [documentsdir stringbyappendingpathcomponent:@"database.sqlite"];
}

and call this method in your did finish with launching method [self copydatabaseifneeded]; hope this will help.

By Vitorlui on May 20 2022

Answers related to “how to copy sqlite database when application is launched in ios?”

Only authorized users can answer the Search term. Please sign in first, or register a free account.