Skip to content

Instantly share code, notes, and snippets.

@adamped
Created January 8, 2016 02:17
Show Gist options
  • Save adamped/06c72a0ba68b979bc397 to your computer and use it in GitHub Desktop.
Save adamped/06c72a0ba68b979bc397 to your computer and use it in GitHub Desktop.
SQLite for iOS
public class SQLite_iOS : ISQLite
{
private SQLiteConnectionWithLock _conn;
public SQLite_iOS ()
{
}
private string GetDatabasePath ()
{
var sqliteFilename = "DatabaseName.db3";
string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder
string libraryPath = Path.Combine (documentsPath, "..", "Library"); // Library folder
var libraryPathFull = Path.Combine (libraryPath, sqliteFilename);
return libraryPathFull;
}
public SQLiteAsyncConnection GetAsyncConnection ()
{
var dbpath = GetDatabasePath ();
var platForm = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS ();
var connectionFactory = new Func<SQLiteConnectionWithLock> (
() =>
{
if (_conn == null)
{
_conn =
new SQLiteConnectionWithLock(platForm,
new SQLiteConnectionString(dbpath, storeDateTimeAsTicks: false));
}
return _conn;
});
var asyncConnection = new SQLiteAsyncConnection (connectionFactory);
return asyncConnection;
}
public void DeleteDatabase ()
{
try{
var path = GetDatabasePath ();
try
{
if (_conn != null)
{
_conn.Close();
}
}
catch (Exception ex)
{
// Best effort close. No need to worry if throws an exception
}
if (File.Exists (path)) {
File.Delete (path);
}
_conn = null;
}
catch(Exception ex){
throw;
}
}
public void CloseConnection()
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
_conn = null;
// Must be called as the disposal of the connection is not released until the GC runs.
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment