Present viewcontroller when not in a viewcontroller

Hello

I’m creating an app that implements a facebook and twitterservice. In my view I have a button that toggles sharing on facebook/twitter or not. If facebook/twitter isnt connected the button will show “connect to”.

When I click the button, a method in my controller (not my viewcontroller) will try to toggle the value because this controller tracks the state of my app. When I’m not connected to a social network my controller will notice and will call the correct service. this service will start a webview to provide the user credentials.

And now my question:
When I’m in my service and I need to provide credentials via a webview. When I want to show this webview I need to pass a viewcontroller that will handle the presenting. How do I provide a viewcontroller here?

Approaches I found:

  • Call the appdelegate singleton and get the current presenting viewcontroller (I find this dirty but correct me if I’m wrong).
  • Since I’m injecting my service into my controller in appdelegate.didFinishLaunchingWithOptions I could inject the UIWindow of the appdelegate and ask for the current presenting viewcontroller (Is almost the same as the first approach)
  • Create a protocol implemented by a viewcontroller. The service has a property that is equal to that protocol and in my app delegate inject the viewcontroller into the service.
  • Have a property in your controller that will be the presentingviewcontroller and let your controller implement the approach #3 protocol. When a function of that protocol is fired, the controller will handle it and use the presentingviewcontroller property for the webview. I only need to inject a viewcontroller into my controller in the appdelegate.
  • Don’t implement anything view related in that service.

My current implementation is approach #3.

If some things are not clear, please let me know.

Any help is appreciated!
Thanks in advance!

Kind regards
Mathias

I would go with the protocol. Have you taken a look at the Apprentice Series Checklist tutorial? It has a very nice explanation on using protocols.

Thank you for your reply!

In my current implementation I’m using a protocol that is a viewcontroller. that viewcontroller is than injected into my service so when my service needs a view I can just call the protocol method and get the response back with a closure.

I was thinking of changing this implementation. Have my controller implement the protocol in my service and create another protocol that will be implemented by a viewcontroller. This gives me the advantage that my service only has to communicate with my controller and my controller will handle which viewcontroller needs to be called. The disadvantage is that I will need to create a protocol in my controller for every service.