Computer >> Hướng Dẫn Máy Tính >  >> Điện Thoại Thông Minh >> iPhone

Tích Hợp Realm Database Vào App iOS CRUD Với Swift – Hướng Dẫn Bước Đi Bước

Xin chào mọi người! Trong bài này chúng ta sẽ học cách thêm Realm database vào app iOS.

Chúng ta sẽ tạo một app ToDo đơn giản để bạn học cách thực hiện các thao tác CRUD (Create, Read, Update, Delete) trong Realm database.

Realm Là Gì?

Tích Hợp Realm Database Vào App iOS CRUD Với Swift – Hướng Dẫn Bước Đi Bước

Realm là mobile database mã nguồn mở thân thiện với developer và dễ dùng. Bạn cũng có thể dùng nó như một lựa chọn thay thế Core Data trong app iOS.

Realm là mobile database cross-platform, nghĩa là bạn có thể dùng nó trong app Android và iOS native và cũng trong app cross-platform như React Native. Nó hỗ trợ Objective-C, Swift, Java, Kotlin, C#, và JavaScript.

Cách Thiết Lập Realm Trong Dự Án iOS Của Bạn

Chúng ta có thể thêm Realm vào project iOS dùng SPM (Swift Package Manager), Cocoa Pods, hoặc Carthage. Ở đây, chúng ta sẽ dùng Cocoa Pods để thêm Realm Pod vào project iOS.

  1. Mở Xcode và tạo project iOS app trống với UIKit và Swift không dùng Core Data.
  2. Đóng Xcode và mở terminal. Điều hướng đến thư mục project bằng terminal.
  3. Chạy lệnh sau để tạo PodFile.
pod init

4.  Khi list nội dung thư mục bạn thấy Podfile mới. Mở file bằng text editor (ở đây dùng Vim). Sửa Podfile như hình dưới. Save và đóng Podfile.

Tích Hợp Realm Database Vào App iOS CRUD Với Swift – Hướng Dẫn Bước Đi Bước

Sau khi chỉ định dependency cho Realm DB, cài dependencies bằng lệnh:

pod install 

Tích Hợp Realm Database Vào App iOS CRUD Với Swift – Hướng Dẫn Bước Đi Bước

Như bạn thấy, đã thêm dependency Realm DB vào project iOS thành công. Chạy lệnh sau để mở project trong Xcode.

open YOUR_APP_NAME.xcworkspace

Lưu ý: sau khi mở Xcode, chắc chắn build project bằng Command+B.

Cách Thiết Kế Giao Diện Người Dùng Trong Realm

Chúng ta sẽ giữ UI app đơn giản. Mở Main.storyboard và tạo UI đơn giản như dưới bằng cách thêm table view với prototype cell. Sau đó embed navigation controller và tạo IBOutlets cho tableview trong ViewController.swift:

Tích Hợp Realm Database Vào App iOS CRUD Với Swift – Hướng Dẫn Bước Đi Bước

Cách Tạo Data Model Trong Realm

Trong app ToDo, mỗi task có tên task và task id. Chúng ta sẽ tạo Model class đại diện cho todo task. Trong project navigator right click và tạo file Swift mới, thêm code dưới:

import Foundation import RealmSwift class ToDoTask:Object { @objc dynamic var tasknote: String? @objc dynamic var taskid: String? }

Ở đây tạo model class tên ToDoTask. Nó kế thừa class Object đi kèm RealmDB. Class này xử lý tất cả quy trình under-the-hood lưu data tạo từ model class này vào database.

Chúng ta cũng thêm hai property: tasknote, là task cần làm, và taskid – cả hai kiểu string. @objc nghĩa là Swift code của bạn visible cho Objective C và dynamic nghĩa là bạn muốn dùng Objective C dynamic dispatch.

Các Chức Năng Cơ Bản Của App CRUD

App sẽ thực hiện các chức năng sau:

  1. Lấy input từ user dùng AlertViewController.
  2. Thêm input vào database và cả table view.
  3. Cho phép user edit input của họ.
  4. Vuốt để xóa row xóa data từ cả table view và database.
  5. Lấy tất cả data (nếu có) từ database và hiển thị trong table view.

Cách Lấy Input Từ User Dùng AlertViewController

Mở ViewController.swift và thêm code dưới vào method ViewDidLoad(). Và tạo function mới tên addTask() thêm code hiển thị alert view controller với text box lấy input từ user.

Bây giờ khi right bar button được nhấn nó sẽ gọi function addTask() hiển thị alertviewcontroller với text field lấy user input.

navigationItem.rightBarButtonItem = UIBarButtonItem(image: .add, style: .done, target: self, action: #selector(addTask)) navigationController?.navigationBar.prefersLargeTitles = true title = "RealmDB"
@objc func addTask() { let ac = UIAlertController(title: "Add Note", message: nil, preferredStyle: .alert) ac.addTextField(configurationHandler: .none) ac.addAction(UIAlertAction(title: "Add", style: .default, handler: { (UIAlertAction) in if let text = ac.textFields?.first?.text { print(text) } })) ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(ac, animated: true, completion: nil) }

Cách Thêm Input Vào Database Và Table View

Để lưu data vào Realm, trước tiên cần lấy instance cho Realm để truy cập tất cả method cần cho CRUD. Tạo property kiểu Realm trong ViewController.swift và khởi tạo trong viewDidLoad().

 var realmDB: Realm!
 override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(image: .add, style: .done, target: self, action: #selector(addTask)) navigationController?.navigationBar.prefersLargeTitles = true title = "RealmDB" realmDB = try! Realm() }

Tạo array rỗng kiểu DataModel (ToDoTask). Array này sẽ chứa tất cả task cần thêm vào table view và database.

Bây giờ bên trong function addTask() sửa closure Add action để lấy user input và tạo random ID cho input đó. Sau đó append vào array và lưu vào database.

var tasks = [ToDoTask]()
 if let text = ac.textFields?.first?.text { //Add data to data model array let t = ToDoTask() t.taskid = UUID().uuidString t.tasknote = text self.tasks.append(t) //Add data to database try! self.realmDB.write { self.realmDB.add(t) } //Update table view UI self.tasktv.reloadData() }

Bây giờ khi chạy app, data sẽ lưu trong database. Nhưng không hiển thị trong table view vì chưa implement delegate methods.

Làm class ViewController implement protocol UITableViewDelegate và UITableViewDataSource và thêm protocol stubs.

Bây giờ bên trong method numberOfRowsInSection, trả về count của array tasks cho số row thêm vào table view. Điều này bằng số element trong tasks array.

 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return tasks.count; }

Điều tiếp theo cần làm là chỉ định nội dung mỗi row. Làm được bằng delegate method cellForRowAt. Ở đây dequeue cell dùng identifier đã chỉ định trong storyboard và set label text là property tasknote của element tasks array.

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "cell") { cell.textLabel?.text = tasks[indexPath.row].tasknote return cell } return UITableViewCell() }

Cách Cho Phép User Edit Input Của Họ

Bây giờ phải cho user edit task đã nhập và update thay đổi trong cả database và UI. Làm được bằng phương pháp tương tự lấy input từ user. Implement delegate method didSelectRowAt sẽ gọi khi user tap row table view.

Thêm code dưới hiển thị AlertViewController với text view. Sau đó update nội dung cell với text nhập, và đồng thời update nội dung database.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let tasktomodify = tasks[indexPath.row] let ac = UIAlertController(title: "Update task", message: nil, preferredStyle: .alert) ac.addTextField(configurationHandler: .none) ac.addAction(UIAlertAction(title: "Ok", style: .default, handler: { (UIAlertAction) in if let text = ac.textFields?.first?.text { if(!text.isEmpty) { try! self.realmDB.write({ tasktomodify.tasknote = text }) self.tasktv.reloadData() } } })) present(ac, animated: true, completion: nil) }

Cách Vuốt Để Xóa Row & Xóa Data Từ Cả Table View Và Database

Ở đây implement tính năng vuốt để xóa trong table view để user xóa task. Nhưng under-the-hood khi user vuốt xóa row thì phải xóa data từ database, data model array, và update UI table view.

Làm được bằng implement delegate method commit editingStyle thêm code sau:

 func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { let tasktoDelete = tasks[indexPath.row] try! realmDB.write({ realmDB.delete(tasktoDelete) self.tasks.remove(at: indexPath.row) self.tasktv.deleteRows(at: [indexPath], with: .fade) }) } }

Cách Lấy Tất Cả Data (Nếu Có) Từ Database Và Hiển Thị Trong Table View

Bây giờ implement operation cuối, Read. Mỗi khi user launch app, nó phải fetch data từ database (nếu có data) và hiển thị trong table view.

Làm được bằng tạo function getTodo trong view controller swift file và thêm code sau:

func getTodos() { //Get all the data from the database let notes = realmDB.objects(ToDoTask.self) //Clear the model data array to prevent duplicates self.tasks.removeAll() /*If the fetched data is not empty then add it to model data array and update the UI */ if(!notes.isEmpty) { for n in notes { self.tasks.append(n) } self.tasktv.reloadData() } }

Mẹo Thêm: Cách Xem Nội Dung Database Trong iOS Simulator

Bây giờ khi chạy app, bạn thấy nó hoạt động như mong đợi. Nhưng làm sao kiểm tra data có thực sự lưu trong database? Chúng ta có thể dùng app MongoDB Realm Studio để xem data lưu trong Realm database của simulator.

Lưu ý phương pháp này chỉ hoạt động khi test app dùng iOS simulator

Trong method viewDidLoad(), thêm dòng code dưới in real file path của app:

 print(realmDB.configuration.fileURL!)

Tích Hợp Realm Database Vào App iOS CRUD Với Swift – Hướng Dẫn Bước Đi Bước

Copy file path in trong console, mở terminal, chạy lệnh sau:

open REALM_FILE_PATH_HERE 
Chắc chắn bạn đã tải MongoDB Realm Studio từ trình duyệt trước khi chạy lệnh trên.

Bây giờ nó sẽ mở RealmFile của app trong MongoDB Realm Studio. Sẽ hiển thị data lưu trong database dạng bảng.

Nếu bạn thay đổi data bằng edit hoặc xóa task, thay đổi sẽ phản ánh trong app MongoDB Realm Studio:

Tích Hợp Realm Database Vào App iOS CRUD Với Swift – Hướng Dẫn Bước Đi Bước

Chúc mừng! Bạn đã làm một app đơn giản implement CRUD operations trong app iOS.