Search code examples
iosswiftvideocore

Swift Instance Member Issue


I'm trying to set up a variable at the top of a class file so I can use it a few lines down. The issue that I'm having is Instance member 'streamWidth' cannot be used on type 'BroadcastViewController'. So I think this is happening because I cannot reference this variable in the main class, I have to use it in a function. Now if this is the case, is there a way I could get around this?

 class BroadcastViewController: UIViewController, VCSessionDelegate {
      @IBOutlet weak var previewView: UIView!
      @IBOutlet weak var btnConnect: UIButton!

      var streamWidth:Int = Int(5)

      var session:VCSimpleSession = VCSimpleSession(videoSize: CGSize(width: streamWidth, height: 720), frameRate: 30, bitrate: 1000000, useInterfaceOrientation: false)

      override func viewDidLoad() {
           super.viewDidLoad()
           previewView.addSubview(session.previewView)
           session.previewView.frame = previewView.bounds
           session.delegate = self

      }

      deinit {
           btnConnect = nil
           previewView = nil
           session.delegate = nil;
      }

      @IBAction func btnConnectTouch(sender: AnyObject) {
           switch session.rtmpSessionState {
           case .None, .PreviewStarted, .Ended, .Error:
                session.startRtmpSessionWithURL("rtmp://east-us.livewx.tv/live", andStreamKey: "fb4843e86976e37" + "?key=" + "e5615d9b171384a0613f")
           default:
                session.endRtmpSession()
           break
       }
       func connectionStatusChanged(sessionState: VCSessionState) {
            switch session.rtmpSessionState {
            case .Starting:
                 btnConnect.setTitle("Connecting", forState: .Normal)
            case .Started:
                 btnConnect.setTitle("Disconnect", forState: .Normal)
            default:
                 btnConnect.setTitle("Connect", forState: .Normal)
            }
      }

      // more functions left out for length reasoning

}

So some of these functions such as deinit, btnConnectTouch, and connectionStatusChanged all use the var session defined at the top.

What I'm asking: How would I go about using variables within the var session:VCSimpleSession?

Many thanks!


Solution

  • You can't use instance variables when initializing other instance variables.

    If I were you, I would change session to an implicitly unwrapped optional and initialize it later:

      var session: VCSimpleSession!
    
      override func viewDidLoad() {
           super.viewDidLoad()
    
           session = VCSimpleSession(videoSize: CGSize(width: streamWidth, height: 720), frameRate: 30, bitrate: 1000000, useInterfaceOrientation: false)
           previewView.addSubview(session.previewView)
           session.previewView.frame = previewView.bounds
           session.delegate = self
      }