在Xamarin.iOS專案中使用預設資料庫
阿新 • • 發佈:2018-11-16
在Xamarin.iOS專案中使用預設資料庫
當開發者準備好一個預設資料庫檔案後,就可以將這個資料庫檔案新增到建立的專案中了。本節將分別在Xamarin.iOS和Xamarin.Android專案中使用預設資料庫。
在Xamarin.iOS專案中使用
在Xamarin.iOS專案中使用預設資料庫的具體操作步驟如下:
(1)建立一個Xamarin.iOS專案,如iOSSQLiteDemo。
(2)將上一節中建立的Documents.db資料庫拖動iOSSQLiteDemo專案的Resources資料夾中。
(3)開啟ViewController.cs檔案,將Documents.db資料庫複製到或移動到Documents目錄下,程式碼如下:
using Foundation; using System; using System.IO; using UIKit; namespace iOSSQLiteDemo { public partial class ViewController : UIViewController { public ViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad () { base.ViewDidLoad (); // Perform any additional setup after loading the view, typically from a nib. var projectBundle = NSBundle.MainBundle; var resourcePath = projectBundle.PathForResource("Documents", "db"); var dirManager = NSFileManager.DefaultManager; string sqlitePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "MyDocuments.db"); Console.WriteLine("資料庫檔案目錄:{0}", sqlitePath); NSError er = new NSError(); dirManager.Copy(resourcePath, sqlitePath, out er); //複製 } public override void DidReceiveMemoryWarning () { base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } } }
執行程式後,會在輸出視窗輸出以下的內容:
資料庫檔案目錄:/Users/mac/Library/Developer/CoreSimulator/Devices/77752D53-9F0F-400C-89BD-A88D1EFD910C/data/Containers/Data/Application/DBD889F8-BB9A-423A-A729-E659A794B18B/Documents/MyDocuments.db