Search code examples
iosswiftuitableviewobservers

how can i call function when data changed?


I have tableview in main.swift and if

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

is called(in appdelegate) my db get new data.

but my view isn't change beacause i didn't call tableview.reloadData

so my question is how can i call tableview.reloadData after

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

called. (I tried Main().myreload (//custom function) but it show fatal error..)


Solution

  • It seems strange that you'd get an application(_:open:options:) call when your database has been reloaded. That function will be called when an external app tells your app to open a URL.

    If that's really true, you need a way to get a message from your app delegate to whoever cares. I would suggest defining and using a NotificationCenter message. Have the view controller that contains the table view call addObserver(forName:object:queue:using:) (or addObserver(_:selector:name:object:), but the first flavor is more Swift-like.)

    Then in your application(_:open:options:) method, use `post(name:object:userInfo:) or one of it's variants to broadcast a notification when the URL open method is called.

    (In general the app delegate should have as little app-specific business logic in it as possible. By using NotificationCenter you can write your app delegate so it doesn't know or care which view controller needs to be notified about the incoming Open URL command.)