添加对sqlLite DB的iPhone支持

时间:2019-04-04 15:59:15

标签: ios sqlite xamarin database-connection

我有一个需要使用Xamarin在iPhone上运行的应用程序。

这是我的Android版本上的外观:

using myMood.Data;
using myMood.Droid.Data;
using System.IO;
using Xamarin.Forms;

[assembly: Dependency(typeof(SQLite_Android))]
namespace myMood.Droid.Data
{
    public class SQLite_Android : ISQLite
    {
        public SQLite_Android() { }
        public SQLite.SQLiteConnection GetConnection()
        {
            var sqliteFileName = "myMood.db3";
            string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var path = Path.Combine(documentsPath, sqliteFileName);
            var conn = new SQLite.SQLiteConnection(path);

            return conn;
        }
    }
}

“ iPhone版本”会如何查找?

1 个答案:

答案 0 :(得分:2)

使用.Net Standard 2.0Xamarin.Forms,您可以在共享代码中直接实现此目标,如下所示

public static SQLiteAsyncConnection GetSQliteAsyncConnection()
    {
        string sqliteFileName = "myMood.db3";
        string dbPath = string.Empty;
        switch (Xamarin.Forms.Device.RuntimePlatform)
        {
            case Device.Android:
                string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                dbPath = Path.Combine(documentsPath, sqliteFileName);
                break;
            case Device.iOS:
                string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
                string libFolder = System.IO.Path.Combine(docFolder, "..", "Library");
                if (!System.IO.Directory.Exists(libFolder))
                {
                    System.IO.Directory.CreateDirectory(libFolder);
                }
                dbPath = System.IO.Path.Combine(libFolder, sqliteFileName);
                break;
            default:
                break;
        }
        var conn = new SQLiteAsyncConnection(dbPath);
        return conn;
    }