使用AVPlayerViewController

时间:2016-03-31 16:09:22

标签: ios swift avplayer

我使用三个函数序列在iOS上使用AVPlayerViewController播放视频:

  1. 首先我将视频文件复制到我的项目根文件夹,然后将它们拖放到xcode项目根

  2. 中,将视频文件添加到我的项目中
  3. 第一个将文件复制到应用程序文档文件夹的函数:

    一个。获取文档路径

    class func getPath(fileName: String) -> String{
    
     let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
     let fileURL = documentsURL.URLByAppendingPathComponent(fileName)
     return fileURL.path!
    
    }
    

    湾复制文件

    class func copyFile(fileName: NSString) {
    
     let dbPath: String = getPath(fileName as String)
     let fileManager = NSFileManager.defaultManager()
    
     if !fileManager.fileExistsAtPath(dbPath) {
    
        let documentsURL = NSBundle.mainBundle().resourceURL
        print(documentsURL)
        let fromPath = documentsURL!.URLByAppendingPathComponent(fileName as String)
    
        var error : NSError?
        do {
            try fileManager.copyItemAtPath(fromPath.path!, toPath: dbPath)
        } catch let error1 as NSError {
            print(error1.localizedDescription)
        }
     }
    }
    
  4. 在我的app delegate application(...)函数中,我调用了Util.copyFile(“EVGS_VID1.MOV”)

  5. 视图控制器中的
  6. 我有一个函数playVideo(fileName:String):

    func playVideo(fileName:String){
    
      let videoPath:String = Util.getPath(fileName) 
      var fileSize : UInt64 = 0
      //Check if file exists
      do {
        let attr : NSDictionary? = try NSFileManager.defaultManager().attributesOfItemAtPath(videoPath)
    
        if let _attr = attr {
            fileSize = _attr.fileSize();
        }
      } catch {
        print("Error: \(error)")
      }
    
      let playerViewController:AVPlayerViewController = AVPlayerViewController()
      var url:NSURL =  NSURL(fileURLWithPath: videoPath,isDirectory: false)
      let player = AVPlayer(URL: url)
      playerViewController.player = player
    
      self.presentViewController(playerViewController, animated: true) {
        playerViewController.player!.play()
      }  
    } 
    
  7. 但是当我在我的视图控制器中调用playVideo时,它会显示没有视频的播放器,我有一个例外:

      

    Error: Error Domain=NSCocoaErrorDomain Code=260 "The file “EVGS_VID1.mov” couldn’t be opened because there is no such file." UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/61169756-1DCE-49B1-99F4-27854DDF4929/Documents/EVGS_VID1.mov, NSUnderlyingError=0x1572bbbf0 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

    我使用相同的函数copyFile和getPath来复制SQLite数据库并且它正在工作

0 个答案:

没有答案