not able to load data with ViewModel - swift

the tableView dataSource is properly set up in the IB
the viewController identity is properly set as well in the IB
this is my viewModel
class StatusCodeViewModel {
let apiClient = APIClient.shared
var statusCodes: [StatusCode] = []
let identifier = "statusCodeCell"
init() {}
func loadStatusCodes() {
apiClient.execute(service: .statusCode) { statusCodes in
self.statusCodes = statusCodes
}
}
}
and the viewController in which I want to load data
class ViewController: UIViewController {
#IBOutlet weak var tableView: UITableView!
var viewModel: StatusCodeViewModel? {
didSet {
if viewModel!.statusCodes.count > 0 {
self.tableView.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
viewModel = StatusCodeViewModel()
viewModel!.loadStatusCodes()
}
}
extension ViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let statusCodes = viewModel!.statusCodes as? [StatusCode] {
return statusCodes.count
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: viewModel!.identifier)
cell?.textLabel!.text = viewModel!.statusCodes[indexPath.row].title
return cell!
}
}
the data count is 0 and no data is shown in the tableView

You have did set on view model which will occur on initialisation.
You will have to implement some kind of callback when the api returns the call - easiest way would be protocol.
protocol StatusCodeViewModelDelegate {
func callFinished()
}
class StatusCodeViewModel {
let apiClient = APIClient.shared
var statusCodes: [StatusCode] = []
let identifier = "statusCodeCell"
var delegate : StatusCodeViewModelDelegate?
init() {}
func loadStatusCodes() {
apiClient.execute(service: .statusCode) { statusCodes in
self.statusCodes = statusCodes
delegate?.callFinished()
}
}
}
Then in your viewController:
override func viewDidLoad() {
super.viewDidLoad()
viewModel = StatusCodeViewModel()
viewModel.delegate = self
viewModel!.loadStatusCodes()
}
func callFinished() {
self.tableView.reloadData()
}
Don't forget to extend for delegate you just made:
class ViewController: UIViewController, StatusCodeViewModelDelegate {
Or, as #rmaddy suggested, in View model change loadStatusCodes to:
func loadStatusCodes(completion: #escaping () -> Void) {
apiClient.execute(service: .statusCode) { statusCodes in
self.statusCodes = statusCodes
}
}
Then, in the viewDidLoad:
override func viewDidLoad() {
super.viewDidLoad()
viewModel = StatusCodeViewModel()
viewModel!.loadStatusCodes {
self.tableView.reloadData()
}
}

//This would do !
func loadStatusCodes(completion: #escaping () -> Void) {
apiClient.execute(service: .statusCode) { statusCodes in
self.statusCodes = statusCodes
completion()
}
}
// And in ViewController:
override func viewDidLoad() {
super.viewDidLoad()
viewModel = StatusCodeViewModel()
viewModel?.loadStatusCodes() {
self.tableView.reloadData()
}
}

Related

Swift async await: how to use with several non async delegates?

I have created this simple example, it is a UITextField with an autocompletion ability, displaying a table view showing asynchronous data that evolves as the user types in the text field.
TextField
import UIKit
protocol TextFieldDelegate {
func autocompletedComponents(
_ textField: TextField,
_ components: #escaping ([String]) -> Void
)
}
class TextField: UITextField {
var components: [String] = []
var tableView = UITableView(frame: .zero)
var autocompletionDelegate: TextFieldDelegate? { didSet { setupUI() } }
// Actions
#objc private func didUpdateText() {
autocompletionDelegate?.autocompletedComponents(self) { [weak self] components in
guard let weakSelf = self else {
return
}
weakSelf.components = components
weakSelf.tableView.reloadData()
weakSelf.updateUI()
}
}
// Event
override func becomeFirstResponder() -> Bool {
tableView.isHidden = false
return super.becomeFirstResponder()
}
override func resignFirstResponder() -> Bool {
tableView.isHidden = true
return super.resignFirstResponder()
}
// Init
override init(frame: CGRect) {
super.init(frame: frame)
internalInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
internalInit()
}
private func internalInit() {
addTarget(
self,
action: #selector(didUpdateText),
for: .editingChanged
)
}
// UI
private func setupUI() {
tableView.dataSource = self
tableView.delegate = self
tableView.showsVerticalScrollIndicator = false
tableView.removeFromSuperview()
superview?.addSubview(tableView)
}
private func updateUI() {
let tableViewHeight = Double(min(5, max(0, components.count))) * 44.0
tableView.frame = CGRect(
origin: CGPoint(
x: frame.origin.x,
y: frame.origin.y + frame.size.height
),
size: CGSize(
width: frame.size.width,
height: tableViewHeight
)
)
}
}
extension TextField: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel?.text = components[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
44.0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
components.count
}
}
ViewController
import MapKit
import UIKit
class ViewController: UIViewController {
private var completion: (([MKLocalSearchCompletion]) -> Void)?
private var searchCompleter = MKLocalSearchCompleter()
#IBOutlet weak var textField: TextField!
override func viewDidLoad() {
super.viewDidLoad()
searchCompleter.delegate = self
textField.autocompletionDelegate = self
}
}
extension ViewController: TextFieldDelegate {
func autocompletedComponents(
_ textField: TextField,
_ components: #escaping ([String]) -> Void
) {
if completion == nil {
completion = { results in
components(results.map { $0.title })
}
}
searchCompleter.queryFragment = textField.text ?? ""
}
}
extension ViewController: MKLocalSearchCompleterDelegate {
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
completion?(completer.results)
}
}
In this example the view controller uses data from MapKit. Now I would like to get rid of the #escaping blocks and replace them with the new async/await syntax.
I have started rewriting the TextField code:
protocol TextFieldDelegate {
func autocompletedComponents(
_ textField: TextField
) async -> [String]
}
#objc private func didUpdateText() {
Task {
let autocompletedComponents = await autocompletionDelegate?.autocompletedComponents(self) ?? []
components = autocompletedComponents
tableView.reloadData()
updateUI()
}
}
However I am stuck in the ViewController, because I don't know what to do with the completion block I was using until now.
Thank you for your help
Here's an implementation using Combine's PassThroughSubject to send the array from MKLocalSearchCompleterDelegate to your autocompletedComponents function which then returns that array to be used in TextField
In ViewController:
class ViewController: UIViewController {
private var searchCompleter = MKLocalSearchCompleter()
var cancellables = Set<AnyCancellable>()
var publisher = PassthroughSubject<[String], Never>()
#IBOutlet weak var textField: TextField!
override func viewDidLoad() {
super.viewDidLoad()
searchCompleter.delegate = self
textField.autocompletionDelegate = self
}
}
extension ViewController: TextFieldDelegate {
func autocompletedComponents(
_ textField: TextField
) async -> [String] {
searchCompleter.queryFragment = textField.text ?? ""
return await withCheckedContinuation { continuation in
publisher
.sink { array in
continuation.resume(returning: array)
}.store(in: &cancellables)
}
}
}
extension ViewController: MKLocalSearchCompleterDelegate {
func completerDidUpdateResults(_ completer: MKLocalSearchCompleter) {
publisher.send(completer.results.map({$0.title}))
}
}
Or you could use your completion closure it would look like this:
func autocompletedComponents(
_ textField: TextField,
_ components: #escaping ([String]) -> Void
) {
return await withCheckedContinuation { continuation in
if completion == nil {
completion = { results in
continuation.resume(returning: results.map { $0.title })
}
}
searchCompleter.queryFragment = textField.text ?? ""
}
}

UITableViewDiffableDataSource are not deinit

I want to use a Combine in my project and face the problem.
Here is the code of the ViewController
import Combine
import UIKit
class ProfileDetailsController: ViewController {
//
// MARK: - Views
#IBOutlet private var tableView: UITableView!
// MARK: - Properties
private typealias DataSource = UITableViewDiffableDataSource<ProfileDetailsSection, ProfileDetailsRow>
private typealias Snapshot = NSDiffableDataSourceSnapshot<ProfileDetailsSection, ProfileDetailsRow>
#Published private var data: [ProfileDetailsSectionModel] = {
return ProfileDetailsSection.allCases.map { ProfileDetailsSectionModel(section: $0, data: $0.rows) }
}()
private lazy var dataSource: DataSource = {
let dataSource = DataSource(tableView: tableView) { tableView, _, model in
let cell = tableView.dequeueReusableCell(withIdentifier: TextFieldTableCell.name) as! TextFieldTableCell
cell.delegate = self
cell.setData(model: model)
return cell
}
dataSource.defaultRowAnimation = .fade
return dataSource
}()
}
// MARK: - Setup binding
extension ProfileDetailsController {
override func setupBinding() {
tableView.registerCellXib(cell: TextFieldTableCell.self)
$data.receive(on: RunLoop.main).sink { [weak self] models in
let sections = models.map { $0.section }
var snapshot = Snapshot()
snapshot.appendSections(sections)
models.forEach { snapshot.appendItems($0.data, toSection: $0.section) }
self?.dataSource.apply(snapshot, animatingDifferences: true)
}.store(in: &cancellable)
}
}
// MARK: - Cell delegates
extension ProfileDetailsController: TextFieldTableCellDelegate {
func switcherAction() { }
}
And here is the code of the cell.
import UIKit
protocol TextFieldTableCellData {
var placeholder: String? { get }
}
protocol TextFieldTableCellDelegate: NSObjectProtocol {
func switcherAction()
}
class TextFieldTableCell: TableViewCell {
//
// MARK: - Views
#IBOutlet private var textField: ZWTextField!
// MARK: - Properties
public weak var delegate: TextFieldTableCellDelegate?
override class var height: CGFloat {
return 72
}
}
// MARK: - Public method
extension TextFieldTableCell {
func setData(model: TextFieldTableCellData) {
textField.placeholder = model.placeholder
}
}
ViewController's deinit was not called.
But when I use this code for ViewController
import UIKit
class ProfileDetailsController: ViewController {
//
// MARK: - Views
#IBOutlet private var tableView: UITableView!
// MARK: - Properties
#Published private var data: [ProfileDetailsSectionModel] = {
return ProfileDetailsSection.allCases.map { ProfileDetailsSectionModel(section: $0, data: $0.rows) }
}()
}
// MARK: - Startup
extension ProfileDetailsController {
override func startup() {
tableView.dataSource = self
tableView.registerCellXib(cell: TextFieldTableCell.self)
}
}
// MARK: - Startup
extension ProfileDetailsController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data[section].data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let model = data[indexPath.section].data[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: TextFieldTableCell.name) as! TextFieldTableCell
cell.delegate = self
cell.setData(model: model)
return cell
}
}
// MARK: - Cell delegates
extension ProfileDetailsController: TextFieldTableCellDelegate {
func switcherAction() {}
}
Everything is fine. deinit called. I tried to set dataSource optional and set it nil on deinit, the same result. With Combine deinit called only when I comment this line:
cell.delegate = self
Does anyone know what's the matter?
Xcode 13.2 iOS 15.2
The Combine stuff is a total red herring. That's why you can't locate the problem; you're looking in the wrong place. The issue is the difference between an old-fashioned data source and a diffable data source. The problem is here:
private lazy var dataSource: DataSource = { // *
let dataSource = DataSource(tableView: tableView) { tableView, _, model in
let cell = tableView.dequeueReusableCell(withIdentifier: TextFieldTableCell.name) as! TextFieldTableCell
cell.delegate = self // *
I've starred the problematic lines:
On the one hand, you (self, the view controller) are retaining the dataSource.
On the other hand, you are giving the data source a cell provider function in which you speak of self.
That's a retain cycle! You need to break that cycle. Change
let dataSource = DataSource(tableView: tableView) { tableView, _, model in
To
let dataSource = DataSource(tableView: tableView) { [weak self] tableView, _, model in
(That will compile, because although self is now an Optional, so is cell.delegate.)

Save textview to CoreData when text change

I'm building a note-taking app for macOS and have a question about saving text whenever the user is editing the NSTextView. I use textDidChange function to detect any changes in the NSTextView and then save the changes to Core Data. However, my code will only save the first edit that the user makes, e.g. if I type hello in the NSTextView, it will only save h instead of hello.
I'm wondering how to fix it? Thank you for your help.
This is the code:
class ViewController: NSViewController, NSTextViewDelegate, NSTableViewDataSource, NSTableViewDelegate {
#IBOutlet var textArea: NSTextView!
#IBOutlet weak var noteList: NSTableView!
let context = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var notes = [Testnote]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
loadData()
textArea.textStorage?.setAttributedString(notes[0].noteItem!)
textArea.delegate = self
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
// MARK: - Tableview stuff
func numberOfRows(in tableView: NSTableView) -> Int {
return notes.count
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "rowNo"), owner: self) as? NSTableCellView {
cell.textField?.stringValue = "sth here"
return cell
}
return nil
}
func tableViewSelectionDidChange(_ notification: Notification) {
if noteList.selectedRow >= 0 {
let selectedNote = notes[noteList.selectedRow]
textArea.textStorage?.setAttributedString(selectedNote.noteItem!)
}
}
func textDidChange(_ notification: Notification) {
if let textview = notification.object as? NSTextView {
notes[0].noteItem = textview.attributedString()
saveData()
}
}
func loadData() {
let request: NSFetchRequest<Testnote> = Testnote.fetchRequest()
do {
notes = try context.fetch(request)
} catch {
print("sth wrong")
}
}
func saveData() {
do {
try context.save()
} catch {
print("Error saving \(error)")
}
}
#IBAction func addButton(_ sender: Any) {
// Create new NSObject and assign values
let newnote = Testnote(context: context)
newnote.noteItem = textArea.attributedString()
(NSApplication.shared.delegate as? AppDelegate)?.saveAction(nil)
}
#IBAction func delete(_ sender: NSButton) {
context.delete(notes[noteList.selectedRow])
do {
try context.save()
} catch {
print("Error")
}
}
}

Not able to load data from firestore to uitableview

I am able to query the data and match it to my model but am not able to display it in my table view. I have 3 files I am working with apart from the storyboard.
Here is the main view controller:
class MealplanViewController: UIViewController {
var db: Firestore!
var mealplanArray = [Mealplan]()
#IBOutlet weak var mealplanTableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
mealplanTableView?.dataSource = self
mealplanTableView?.delegate = self
db = Firestore.firestore()
loadData()
// Do any additional setup after loading the view.
}
func loadData() {
userEmail = getUserEmail()
db.collection("Meal_Plans").getDocuments() {querySnapshot , error in
if let error = error {
print("\(error.localizedDescription)")
} else {
self.mealplanArray = querySnapshot!.documents.compactMap({Mealplan(dictionary: $0.data())})
print(self.mealplanArray)
DispatchQueue.main.async {
self.mealplanTableView?.reloadData()
}
}
}
}
func getUserEmail() -> String {
let user = Auth.auth().currentUser
if let user = user {
return user.email!
} else {
return "error"
}
}
}
// MARK: - Table view delegate
extension MealplanViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return mealplanArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCell(withIdentifier: "MealplanTableViewCell", for: indexPath)
let mealplanRow = mealplanArray[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "MealplanTableViewCell") as! MealplanTableViewCell
cell.setMealplan(mealplan: mealplanRow)
return cell
}
}
And here is the cell where I am showing one of the queried values:
class MealplanTableViewCell: UITableViewCell {
#IBOutlet weak var mealplanNameLabel: UILabel!
func setMealplan(mealplan: Mealplan) {
// Link the elements with the data in here
mealplanNameLabel.text = mealplan.mpName
print(mealplan.mpName)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
And finally, here is the data model:
import Foundation
import Firebase
protocol MealplanSerializable {
init?(dictionary:[String:Any])
}
struct Mealplan {
var mealplanId:String
var mpName:String
]
}
}
extension Mealplan : MealplanSerializable {
init?(dictionary: [String : Any]) {
guard let
let mealplanId = dictionary["mealplanId"] as? String,
let mpName = dictionary["mpName"] as? String,
else { return nil }
self.init(mealplanId: mealplanId, mpName: mpName)
}
}
I am getting just an empty table view with no data in it.

Application stuck on splash screen

My application gets stuck on the splash screen when running. It does already have a storyboard entry point which points to the view controller named studentsViewController so I don't know why it isn't working. There is no crash.
StudentsViewController:
import UIKit
class StudentsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var currentClass = VirtualRewardsClient.sharedInstance.getClass()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
tableView.registerClass(StudentTableViewCell.self, forCellReuseIdentifier: "studentCell")
Class.sharedInstance.addStudent("Dhruv")
Class.sharedInstance.printClass()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return Class.sharedInstance.students.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCellWithIdentifier("studentCell") as StudentTableViewCell
return cell
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
VirtualRewardsClient.swift
import UIKit
class VirtualRewardsClient{
class var sharedInstance: VirtualRewardsClient{
struct Static{
static var instance = VirtualRewardsClient()
}
return Static.instance
}
func getClass() -> Class{
if let data = NSUserDefaults.standardUserDefaults().objectForKey(classKey) as? NSData{
let unarc = NSKeyedUnarchiver(forReadingWithData: data)
unarc.setClass(Class.self, forClassName: "Class")
let currentClass = unarc.decodeObjectForKey("root") as Class
Class.sharedInstance.students = currentClass.students
Class.sharedInstance.teacher = currentClass.teacher
return currentClass
}
return Class()
}
}
Class.swift
import Foundation
import UIKit
let classKey = "CLASS_KEY"
class Class: NSObject{
let defaults = NSUserDefaults.standardUserDefaults()
class var sharedInstance: Class{
struct Static{
static var instance: Class = VirtualRewardsClient.sharedInstance.getClass()
}
return Static.instance
}
var students:[Student] = [Student]()
var teacher = Teacher(currentClass: sharedInstance)
func addStudent(name: String, value: Int){
students.append(Student(name: name, startingPoints: value))
defaults.setObject(NSKeyedArchiver.archivedDataWithRootObject(Class.sharedInstance), forKey: classKey)
VirtualRewardsClient.sharedInstance.getClass()
}
func addStudent(name: String){
students.append(Student(name: name))
defaults.setObject(NSKeyedArchiver.archivedDataWithRootObject(Class.sharedInstance), forKey: classKey)
VirtualRewardsClient.sharedInstance.getClass()
}
func printClass(){
for i in students{
println("Student: \(i.name), Points: \(i.points)")
}
}
}