【问题标题】:ViewController.swift may not load correctlyViewController.swift 可能无法正确加载
【发布时间】:2015-08-12 14:24:13
【问题描述】:

我正在使用 xcode 6 和 swift 制作带有视频聊天的应用程序 - 使用 OpenTok。 我有 2 个场景“菜单”和“视频”。从我使用的菜单中:

self.performSegueWithIdentifier("StreamScene", sender: self)

在按钮内转到“视频”视图控制器。第一次加载我的应用程序时一切正常,但是当我从“视频”导航回“菜单”,然后再次从“菜单”导航到“视频”时,它不起作用,我看不到订阅者到我的会话,但是当我关闭我的应用程序但仍然让视频会话运行并再次启动我的应用程序并导航到“视频”视图控制器时它可以工作 - 这是因为我的视图控制器可能无法正确加载?我还使用 performrSegueWithIdentifier 导航回来。

来自视频视图控制器的代码

import UIKit

//Api key
private let ApiKey = "45309032"
//Session ID
private let SessionID = HttpPost.SessionId
//Token
private let Token = HttpPost.Token

let SubscribeToSelf = false
class ViewController: UIViewController, OTSessionDelegate,     OTSubscriberKitDelegate, OTPublisherDelegate {


@IBOutlet weak var DoctorDeclienBtn: UIButton!

var Session : OTSession?
var Publisher : OTPublisher?
var Subscriber : OTSubscriber?

var http = HttpPost()


override func viewDidLoad() {
    super.viewDidLoad()

}


override func viewWillAppear(animated: Bool) {

    // Step 2: As the view comes into the foreground, begin the connection process.
    //ConnectToSession()
    println("Session ID " + SessionID)
    println("Token " + Token)



    // Do any additional setup after loading the view, typically from a nib.

    // Step 1: As the view is loaded initialize a new instance of OTSession

    if(HttpPost.Role == "0")
    {
        DoctorDeclienBtn.hidden = true
    }


    ConnectToSession()


}


@IBAction func GoBackBtn(sender: AnyObject) {
    self.performSegueWithIdentifier("a", sender: self)
    DisconnectSession()
}



@IBAction func DoctorDeclineBtn(sender: AnyObject) {

    http.HttpPostVideoEnded("access_token=" + HttpPost.AccessToken, URL: "http://95.85.53.176/nhi/api/app/consultation/end/", completionHandler: {(EndSuccess: Int32) -> () in

        if(EndSuccess == 1)
        {
            if let session = self.Session
            {
                var Error : OTError?
                session.disconnect(&Error)


                if let error = Error
                {

                }

            }

        }


    })
}


// 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 ConnectToSession ()
{

    Session = OTSession(apiKey: ApiKey, sessionId: SessionID, delegate: self)

    if let session = self.Session
    {
        var Error : OTError?
        session.connectWithToken(Token, error: &Error)


        if let error = Error
        {

        }

    }
}

/**
* 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 PublishToSession()
{

    Publisher = OTPublisher(delegate: self)

    var Error : OTError?

    Session?.publish(Publisher, error: &Error)

    if let error = Error
    {
        //Some message
    }


    //The resolutuon of current device
    var sizeRect = UIScreen.mainScreen().applicationFrame
    var width = sizeRect.size.width
    var height = sizeRect.size.height

    Publisher!.view.frame = CGRect(x: width-(width/4), y: height * (4/5), width: width/4, height: height/3)
    view.addSubview(Publisher!.view)


}


//Unpublish to session
func UnPublishToSession()
{
    Publisher = OTPublisher(delegate: self)

    var Error : OTError?

    Session?.unpublish(Publisher, error: &Error)

    if let error = Error
    {
        //Some message
    }

    Publisher!.view.removeFromSuperview()
    self.Publisher = nil

}


/**
* Instantiates a subscriber for the given stream and asynchronously begins the
* process to begin receiving A/V content for this stream. Unlike doPublish,
* this method does not add the subscriber to the view hierarchy. Instead, we
* add the subscriber only after it has connected and begins receiving data.
*/
func SubscribeToStream(stream : OTStream) {
    if let session = self.Session {
        Subscriber = OTSubscriber(stream: stream, delegate: self)

        var Error : OTError?
        session.subscribe(Subscriber, error: &Error)
        if let error = Error {

        }
    }
}

func DisconnectSession()
{
    if let session = self.Session
    {
        var Error : OTError?
        session.disconnect(&Error)


        if let error = Error
        {
            NSLog("Disconnect failed")
        }

    }
}

/**
* Cleans the subscriber from the view hierarchy, if any.
*/
func UnsubscribeStream() {
    if let subscriber = self.Subscriber {
        var Error : OTError?
        Session?.unsubscribe(Subscriber, error: &Error)
        if let error = Error {

        }

        subscriber.view.removeFromSuperview()
        self.Subscriber = nil
    }
}

// MARK: - OTSession delegate callbacks

func sessionDidConnect(session : OTSession) {
    NSLog("sessionDidConnect (\(session.sessionId))")

    // Step 2: We have successfully connected, now instantiate a publisher and
    // begin pushing A/V streams into OpenTok.
    PublishToSession()
}

func sessionDidDisconnect(session : OTSession) {
    NSLog("Session disconnected (\( session.sessionId))")
    UnPublishToSession()
    self.performSegueWithIdentifier("a", sender: self)
}

func session(session: OTSession, streamCreated stream: OTStream) {
    NSLog("session streamCreated (\(stream.streamId))")

    // Step 3a: (if NO == subscribeToSelf): Begin subscribing to a stream we
    // have seen on the OpenTok session.
    if Subscriber == nil && !SubscribeToSelf{
        SubscribeToStream(stream)
    }


}

func session(session: OTSession, streamDestroyed stream: OTStream) {
    NSLog("session streamDestroyed (\(stream.streamId))")

    if Subscriber?.stream.streamId == stream.streamId {
        UnsubscribeStream()
    }
    DisconnectSession()
}

func session(session: OTSession, connectionCreated connection : OTConnection) {
    NSLog("session connectionCreated (\(connection.connectionId))")
}

func session(session: OTSession, connectionDestroyed connection : OTConnection) {
    NSLog("session connectionDestroyed (\(connection.connectionId))")

}

func session(session: OTSession, didFailWithError error: OTError) {
    NSLog("session didFailWithError (%@)", error)

}

// MARK: - OTSubscriber delegate callbacks

func subscriberDidConnectToStream(subscriberKit: OTSubscriberKit) {
    NSLog("subscriberDidConnectToStream (\(subscriberKit))")


    var sizeRect = UIScreen.mainScreen().applicationFrame
    var width = sizeRect.size.width
    var height = sizeRect.size.height

    if let view = Subscriber?.view {
        view.frame =  CGRect(x: 0, y: 0, width: width, height: height + 20)
        self.view.addSubview(view)
        self.view.sendSubviewToBack(view)

    }
}

func subscriber(subscriber: OTSubscriberKit, didFailWithError error : OTError) {
    NSLog("subscriber %@ didFailWithError %@", subscriber.stream.streamId, error)

}

// MARK: - OTPublisher delegate callbacks

func publisher(publisher: OTPublisherKit, streamCreated stream: OTStream) {

    NSLog("publisher streamCreated %@", stream)


    // Step 3b: (if YES == subscribeToSelf): Our own publisher is now visible to
    // all participants in the OpenTok session. We will attempt to subscribe to
    // our own stream. Expect to see a slight delay in the subscriber video and
    // an echo of the audio coming from the device microphone.

    if Subscriber == nil && !SubscribeToSelf{
        SubscribeToStream(stream)
    }


}

func publisher(publisher: OTPublisherKit, streamDestroyed stream: OTStream) {
    NSLog("publisher streamDestroyed %@", stream)

    if Subscriber?.stream.streamId == stream.streamId {
        UnsubscribeStream()
    }
}

func publisher(publisher: OTPublisherKit, didFailWithError error: OTError) {
    NSLog("publisher didFailWithError %@", error)
}

func showAlert(message: String) {
    // show alertview on main UI
    dispatch_async(dispatch_get_main_queue()) {
        let al = UIAlertView(title: "OTError", message: message, delegate: nil, cancelButtonTitle: "OK")
    }
}

}

【问题讨论】:

  • 您可以从视频视图控制器的 viewDidLoad 位以及 viewWillAppear 位发布一些代码吗?基本上,如果它没有像你描述的那样工作,问题就会出现在某个地方
  • 我已经添加了我的整个“视频”视图控制器@fr0s1yjack。感谢您的回复
  • 如果将 ConnectToSession() 放入 viewDidLoad 而不是 viewWillAppear 会发生什么?
  • 没什么变化 - 我遇到了同样的问题。

标签: swift uiviewcontroller xcode6 opentok


【解决方案1】:

您需要仔细考虑转换的逻辑。

在您提供的代码中,您基本上说:“当订阅者的流被销毁时,从流中取消发布和取消订阅,然后转换回菜单”。

首先,你应该注意你要在哪里清理哪种状态。照原样,您假设其他参与者将离开,然后在 session:streamDestroyed: 方法内进行清理和转换。相反,使用该方法只清理订阅者。同样,清理sessionDidDisconnect: 方法中的发布者。通过清理,我基本上是指分别调用 UnsubscribeToStream() 和 UnPublishToSession() 方法。

接下来,您应该考虑什么才能触发结束通话的问题。假设其他参与者将首先离开对于简单的情况是可以的,但它是一个更好的设计来为这个离散的动作制作一个方法,这样你就可以从多个地方调用它。至于方法需要做什么,其实就是调用session.disconnect()那么简单。这将触发上述清理发布者和订阅者的方法。现在,您完全错过了断开连接,这就是您在返回“视频”视图时没有开始订阅的原因(所有设置呼叫的代码只能从 sessionDidConnect: 方法内部调用)。

最后,需要触发 segue。在我看来,您应该在清理发布者之后,在 sessionDidDisconnect: 方法的末尾执行此操作。

【讨论】:

  • 你好@Ankur。谢谢你的回答。抱歉,我之前无法给您反馈。我刚刚再次启动了这个项目。我尝试了您的解决方案,但仍然无法正常工作。我已经编辑了我对最新解决方案的答案。如您所见,当我返回菜单视图时,我断开了连接。从菜单视图中,我导航到视频视图并再次开始连接。我的订阅者没有加载,我收到一条错误消息:{NSLocalizedDescription=尝试订阅流时超时。}
  • @LocDaiLe 这个错误是持续发生还是间歇性发生?该特定错误与网络连接有关。尝试设备上的 OpenTok Connectvity Doctor [itunes.apple.com/us/app/opentok-connectivity-doctor/… 以查看网络配置是否正确。
猜你喜欢
  • 1970-01-01
  • 2020-09-21
  • 2018-12-15
  • 2019-08-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多