Morgan Evans Media Morgan Evans Media - 6 months ago 34
iOS Question

Xcode swift - unresolved identifier error

Please help me to edit my code. I cant seem to fix this error.

import UIKit
import AVKit
import AVFoundation
import MediaPlayer

class ViewController: UIViewController {

let avPlayerViewControler = AVPlayerViewController()
var avPlayer:AVPlayer?
var videoNumber:Int!
var url:String!

override func viewDidLoad() {
super.viewDidLoad()

let urlpathString:String? = NSBundle.mainBundle().pathForResource("url", ofType: "mp4")

if let urlPath = urlpathString {

switch videoNumber {
case 1 : url="20"
case 2 : url="10"
default : break
}
let movieUrl = NSURL(fileURLWithPath: urlPath)

}
self.avPlayer = AVPlayer(URL: movieUrl)
self.avPlayerViewControler.player = self.avPlayer

}

@IBAction func Cool(sender: UIButton) {
videoNumber=1
}
}

Answer

You have to move the two lines regarding the avPlayer and avPlayerViewControler inside the if since the constant movieUrl is only available inside that scope - it only exists inside the scope it was defined in, it does not exist outside of the if-block!

override func viewDidLoad() {
    super.viewDidLoad()

    let urlpathString:String? = NSBundle.mainBundle().pathForResource("url", ofType: "mp4")

    if let urlPath = urlpathString {

        switch videoNumber {
            case 1 : url="20"
            case 2 : url="10"
            default : break
        }
        let movieUrl = NSURL(fileURLWithPath: urlPath)
        self.avPlayer = AVPlayer(URL: movieUrl)
        self.avPlayerViewControler.player = self.avPlayer
    }
}