【问题标题】:Xcode swift - cannot invoke 'pathForResource' with an argument list of type '(String!)'Xcode swift - 无法使用“(String!)”类型的参数列表调用“pathForResource”
【发布时间】:2016-10-09 07:38:03
【问题描述】:

请帮我修复我的代码,因为我有以下错误:

无法使用类型为“(字符串!)”的参数列表调用“pathForResource”

错误就在这行代码上:

let urlpathString:String? = NSBundle.mainBundle().pathForResource(url)

我的完整代码:

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()     
    }

    func playVideo() {
        switch videoNumber {
            case 1 : url="20"
            case 2 : url="10"
            default : break

            let urlpathString:String? = NSBundle.mainBundle().pathForResource(url)

            if let urlPath = urlpathString {
                let movieUrl = NSURL(fileURLWithPath: urlPath)
                self.avPlayer = AVPlayer(URL: movieUrl)
                self.avPlayerViewControler.player = self.avPlayer

            }
        }
    }

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

    @IBAction func Button2(sender: UIButton) {
        videoNumber=2
        playVideo()
    }
}

【问题讨论】:

    标签: ios objective-c xcode swift error-handling


    【解决方案1】:

    NSBundle 没有简单的pathForResource 方法,至少有第二个参数,例如pathForResource:ofType:

    既然您无论如何都需要NSURL,请使用URL 发布的API,将整个if let 表达式替换为

    func playVideo() {
      switch videoNumber {
        case 1 : url="20"
        case 2 : url="10"
        default : break
      }
    
      if let movieUrl = NSBundle.mainBundle().URLForResource(url, withExtension: "mp4") {
         self.avPlayer = AVPlayer(URL: movieUrl)
         self.avPlayerViewControler.player = self.avPlayer
      }
    }
    

    您必须将mp4 更改为预期的扩展名。

    【讨论】:

    • 您好!谢谢你!我已经用你的代码替换了整个 if let 表达式。但我仍然收到错误。请帮忙
    • 不可能出现同样的错误,因为使用了不同的 API。当然let urlpathString:String? = NSBundle.mainBundle().pathForResource(url)这行也得删掉
    • 我已经替换了代码,不再出现错误。但是视频不会在按钮单击时播放。有什么建议吗?谢谢
    • 如果 let movieUrl = NSBundle.mainBundle().URLForResource(url, withExtension: "mp4") { 这可能是为什么?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多