Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift/IOS how to update using observers

Tags:

ios

swift

In Android, we have mutable live data object when we update it let say on a different thread we attached to it an observer. When the object gets updated the observer is listening and update the UI accordingly.

liveDataService.setValue(response); ==> updating the object with new data

And in the Activity(let say like TableViewController for swift/IOS)

We put the observer

liveDataService.observeForever(s -> {
            Log.d(TAG, getString(R.string.service_observer_message));
            updateUI(s);
        }); ==> When liveDataService changes we update the UI

Now I want to do the same for Swift/IOS

I see the function

addObserver(_:forKeyPath:options:context:)

But I can not attach it to an Array that gets the update in the background only to NSObject

What is the best method to accomplish this task?

Thanks Eran

like image 577
Eran Gross Avatar asked Oct 24 '25 20:10

Eran Gross


2 Answers

As per my understanding, you should use local notifications for sending data with addObserver and postNotification to achieve this. find sample code for same.

 let imageData:[String: UIImage] = ["image": image]

// post a notification

  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageData) 

// Register to receive notification in your class

 NotificationCenter.default.addObserver(self, selector: #selector(self.receiveData(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

// handle notification

func receiveData(_ notification: NSNotification) {


if let image = notification.userInfo?["image"] as? UIImage {


}

}
like image 162
Parth Avatar answered Oct 26 '25 12:10

Parth


You can use didSet property observe. It respond when property value change.

var dataArray  = [String]() {
    didSet {
        print(“Array Count = \(dataArray.count)”)
    }
}

when you append data in dataArray its call the dataArray property observe and print the Array Count

like image 20
gaurav bajaj Avatar answered Oct 26 '25 10:10

gaurav bajaj