karl karl - 4 months ago 21
Swift Question

Presenting ViewController anew does not re-initialize it

I have a viewController (videocallVC) that I want to initialize every time it comes into view/loads.
Currently, the videocallVC only initialize the first time. If I leave the videocallVC, go to another viewController and come back to the videocallVC it holds the last session in memory and does not "refresh".

How can I make sure that every time I present the videocallVC it is initialized anew ?

import OpenTok

class videocallVC: UIViewController, OTSessionDelegate, OTSubscriberKitDelegate, OTPublisherDelegate {

@IBOutlet var subscribeView: UIView!
@IBOutlet var publishView: UIView!

let apiKey = "xxxxxxx"

var session : OTSession?
var publisher : OTPublisher?
var subscriber : OTSubscriber?
var connection : OTConnection?


override func viewDidLoad() {
super.viewDidLoad()

session = OTSession(
apiKey: apiKey,
sessionId: variableInstance.sessionID,
delegate: self)
}

override func viewWillAppear(animated: Bool) {
doConnect()
}

// MARK: - OpenTok Methods

/**
* Asynchronously begins the session connect process. Some time later, we will
* expect a delegate method to call us back with the results of this action.
*/
func doConnect() {
if let session = self.session {
var maybeError : OTError?
session.connectWithToken(variableInstance.tokboxToken, error: &maybeError)
if let error = maybeError {
showAlert(error.localizedDescription)
}
}
}

/**
* Sets up an instance of OTPublisher to use with this session. OTPubilsher
* binds to the device camera and microphone, and will provide A/V streams
* to the OpenTok session.
*/
func doPublish() {
publisher = OTPublisher(delegate: self)

var maybeError : OTError?
session?.publish(publisher, error: &maybeError)

if let error = maybeError {
showAlert(error.localizedDescription)
}

view.addSubview(publisher!.view)
publisher!.view.frame = publishView.frame

}


There is more code to the videocallVC but I gues this is sufficient to understand the problem.

Any help would be very much appreciated ! Thank you.

Answer

The method viewDidLoad is only called once. The method viewWillAppear is called every time the view will appear. So if you need to do things every time the view will appear, move it to that method (you may also use viewDidAppear if the UI behaviour makes sense). This may apply to the session = OTSession( ... ) snippet.

It may also be possible, that in your code things get initialized, then stored in a variable and later, if the variable is not nil no new initialization is done. You may solve that by setting those variables to nil in viewWillAppear.

However, without knowing all details, this may be a likely solution but still a shot in the dark :-)

Comments