WatchConnectivity how to share session among multiple WKInterfaceControllers? - ios

I have a situation where I need to share WCSession among multiple WKInterfaceControllers. Singleton approach won't work, once you set delegate to a class, all delegates in the other classes are invalidated. Scenario: interface A send and receive data, based on the data content, present interface B. Tap on interface B, will request and receive additional data. How would you share the WCSession between A and B ?

The other answer doesn't explain that an app-wide session would work.
You can use an app-wide WCSession singleton which would be available to all your interface controllers. You simply instantiate a session manager very early in the app life cycle, and let it be its own delegate.
Instead of trying to make each interface controller handle the session delegation (which won't work well), a session manager (singleton) can handle all the transfers for your interface controllers.
As mentioned in the other answer, you could then use notifications to let interested interface controllers know when their new data arrives.
Using a modular approach, such as a session or data manager, helps to keep such code out of a controller, where it really doesn't belong. It also makes it easier to test and utilize each module.
I won't repeat the code here, as there have already been several existing answers posted on Stack Overflow, as well as
articles on the web, which cover this technique in detail. For example:
Using WCSession with more than one ViewController
WatchConnectivity: Say Hello to WCSession
You'll often find these types of answers within narrower questions that ask how to share data between, say, a watch app and its complication controller.

Use NSNotification and listen for changes in all view controllers.

Related

Keeping a WKWebView and it's UIViewController in the background running and accessible from multiple ViewControllers

Background: In order to make web requests to an API endpoint, I need to scrape a website and retrieve a token every 25-30 seconds. I'm doing this with a WKWebView and injecting some custom JavaScript using WKUserScript to retrieve AJAX response headers containing the token. Please focus on the question specifically and not on this background information - I'm attempting this entirely for my own educational purposes.
Goal
I will have different 'model' classes, or even just other UIViewControllers, that may need to call the shared UIViewController to retrieve this token to make an authenticated request.
Maybe I might abstract this into one "Sdk" class. Regardless, this 'model' SDK class could be instantiated and used by any other ViewController.
More info
I would like to be able to call the UIViewController of the WKWebView and retrieve some data. Unless I re-create it every 25 seconds, I need to run it in the background or share it. I would like to be able to run a UIViewController 'in the background' and receive some information from it once WKWebView has done it's thing.
I know there are multiple ways of communicating with another ViewController including delegation and segueing. However, I'm not sure that these help me keep the view containing the WKWebView existing in the background so I can call it's ViewController and have it re-perform the scrape. Delegation may work for normal code, but what about one that must have the view existing? Would I have to re-create this WKWebView dynamically each time a different model, or view controller, were to try and get this token?
One post suggests utilising ContainerViewControllers. From this, I gather that in the 'master' ViewController (the one containing the other ones), I could place the hidden WKWebView to do it's thing and communicate to the child view controllers that way via delegation.
Another post suggests using AppDelegate and making it a shared service. I'm completely against using a Singleton as it is widely considered an anti-pattern. There must be another way, even if a little more complex, that helps me do what I want without resorting to this 'cheat'.
This post talks about communicating between multiple ViewControllers, but I can't figure out how this would be useful when something needs to stay running and executing things.
How about any other ways to do this? Run something in a background thread with a strong pointer so it doesn't get discarded? I'm using Xcode 9.2, Swift 4, and iOS 11. As I'm very new to iOS programming, any small code examples on this would be appreciated.
Unfortunately, WKWebView must be in the view hierarchy to use it. You must have added it as a sub view of an on-screen view controller.
This was fine for me. I added this off-screen so it was not visible. Hidden attribute might have worked as well. Either way you must call addSubview with it to make it work.
There are some other questions and answers here which verify this.
Here is a way if you don't wish to use a singleton.
1- In the DidFinishlaunchingWithOptions, Make a timer that runs in the background and call a method inside the app delegate Called FetchNewToken.
2- In FetchNewToken, make the call needed and retrieve the new token (you can use alamofire or any 3rd library to make the call easier for you).
Up on successfully retrieving the token, save it in NSUserDefaults under the name upToDateToken
You can access this token anywhere from the application using NSUserDefaults and it will always be up to date.

Does VC-VC communication change with Swift?

In the past I would do:
MainViewController pushes ProfileViewController
In willPerformSegue, give the target ProfileViewController access to a profile instance
Also set target delegate to self
ProfileViewController allows the user to edit their profile
User presses save
ProfileViewController calls sends message didSave to delegate and pops out
MainViewController handles the didSave by saving the model to disk
All of this still works in Swift. My question is: is this still the favored way to handle inter-VC communication in the Swift era?
Yes, it is. Or rather you can do it the same way.
Swift is just another language, which uses the same libraries.
Things you describe related to those libraries, the notion of UIViewController is defined within them, so everything is done the same way.
The delegate pattern works well, but it's not the only way to communicate between controllers, and it can't be "best" in all cases. The best way depends on the task you're trying to solve, not the language you use.
My question is: is this still the favored way to handle inter-VC communication in the Swift era?
With the caveat that the method name is -performSegueWithIdentifier:sender:, that's fine way to do it, and as far as I know it's still fine under Swift. Apple didn't make any announcement at WWDC 2015 that things have changed in this respect, and the UIViewController interface doesn't suggest any more compelling ways to configure a view controller during a segue.
MainViewController handles the didSave by saving the model to disk
That's also fine, since MainViewController is ProfileViewController's delegate, and it sounds like ProfileViewController isn't aware of the entire model. In other circumstances, it might make sense for a view controller to use the model directly, and for the model to handle saving. But that's a design issue, not a Swift vs. Objective-C issue.

How to use the data from a notification that is meant to be used in VC A , when i am in VC B

Ok so i have been trying to figure out how to do this for a while but i did not seem to find way to do it. Also i would like the proper way to do this.
A server that i have is sending notifications every 30 seconds to my device. Lets say i am in ViewController B, but the data that is received by the notification is ment to be displayed/used in ViewController A.
Lets say i received two notifications while i was in ViewController B. Then i navigate to ViewController A. How would i get it to display the most recent data that was received by the notification?
You should receive the notification in a (global) 3rd object that will store them, then when the VC A is displayed you'll easily retrive them from that object...
Follow the "shared instance" path used by many iOS classes (even if someone don't like it 'cause they read singletons are evil, I think this's the perfect case to use it).
You can solve it this way:
Create at startup your singleton class that will receive the notifications and keep them in a queue.
Add to the singleton methods to read/consume the notification queue.
From any class you need the data (i.e. your view controller) get the infos you need via the methods above.
This solution keep data manager (notification handling) and presentation (the view controller) separated, I don't see any real cons...
Again, I know singletons have a bad reputation (and often people abuse of this pattern) but you know Apple's NSNotificationCenter have a +defaultCenter class method that return the shared instance (another word for singleton) so I'm quite sure this's the case to use it.
here http://www.daveoncode.com/2011/12/19/fundamental-ios-design-patterns-sharedinstance-singleton-objective-c/ you can find a good example how to implement the +sharedInstance (or +defaultCenter or whatever you want to call it) method.
Hope this help.

Making one view controller listen to another

So I have two view controllers. One has autocomplete for location search, and all it does is let the user use the google places api to get an address. The other lets the user do a keyword search and actually displays results in a table view(with a custom uitablecell).
I want to make it so that the I can take the address from one view controller, execute a search and use the code that draws the table in the other controller to draw my results.
In other words, I'm looking for a way for one view controller to trigger a message and the other view controller to listen.
Is there a way to do this?
When there are more than one receiver, use Notifications. We can set only one delegate.
When to use NSNotificationCenter Checklist:
You need a one-to-many relationships. You need few observers to react on a particular notification. Example: reachability notifications. When your network reachability changes, e.g. wi-fi becomes unavailable, all of the objects subscribed to this type of notifications will receive them and can process accordingly.
By design you encourage loose coupling. In the example above, producer that sends a ‘reachability changed’ notification doesn’t know anything about possible observers of this notifications. There could be few of them or none. Same true for observers, they don’t need to know anything about producers of this notification.
When to use Delegates Checklist:
Delegates should always be used only for one-to-one relationships.
Use delegates if you encourage tight coupling. Bear in mind, by using delegates you create more interdependency between objects and have more coordination with information flow.
A very good example of delegates would be UITableView. UITable ViewDelegate encourages more information flow and creates more interdependency between view controller and table view.
Here is what you need
Notification or Delegate
link 2

Communicating view change

Is it best practice to communicate an event or something similar (like successful login) through NSNotificationCenter or is there any other controlling mechanism you can recommend?
As for me I do not like to use NSNotificationCenter because it is overloaded with a big amount of system and custom events.
If you add a lot of observers to NSNotificationCenter, you should not forget to remove these observers, also sometimes it is difficult to know the sequence, in which observing methods will be called. Also NSNotificationCenter doesn't check or manage adding the same observer more than one time(it sometimes becomes a real trouble, when you addObserver not in the correct place).
So: Why just not create some LoginManager singleton which will contain all the needed data and manage all login behaviour? It will contain some data as : isAuthorithed, etc.. And of course if you need to implement Observer pattern, your singleton class can implement this in the same way as NSNotificationCenter
That depends on what the event is and what classes are likely to need to know about it. For login / logout notifications are a good option because many different classes may want to respond tithe event. That doesn't mean that you can't also have a delegate / block callback for use by the class which triggered the login.
Generally, notifications for general things that could be interesting to many classes and direct callbacks for specific events (and the instance which triggered the event).

Resources