Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Calculator

0

89
Views
Swift/IOS how to update using observers

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

8 months ago · Santiago Trujillo
3 answers
Answer question

0

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 {


}

}
8 months ago · Santiago Trujillo Report

0

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

8 months ago · Santiago Trujillo Report

0

There are multiple ways how to do that.

The one that's closest to your Android solution should be Key Value Observing: https://developer.apple.com/documentation/swift/cocoa_design_patterns/using_key-value_observing_in_swift

If you want to read more about that topic: https://www.swiftbysundell.com/posts/observers-in-swift-part-1

8 months ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2023 PeakU Inc. All Rights Reserved.