How to Play Videos PHAsset in iOS?
After several days experiment finally I come upon a solution,
Import File
import AVKit
From PHAsset
static func playVideo (view:UIViewController, asset:PHAsset) {
guard (asset.mediaType == PHAssetMediaType.Video)
else {
print("Not a valid video media type")
return
}
PHCachingImageManager().requestAVAssetForVideo(asset, options: nil, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [NSObject : AnyObject]?) in
let asset = asset as! AVURLAsset
dispatch_async(dispatch_get_main_queue(), {
let player = AVPlayer(URL: asset.URL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
view.presentViewController(playerViewController, animated: true) {
playerViewController.player!.play()
}
})
})
}
From AppLocalUrl
static func playVideo (view:UIViewController, appLocalUrl:NSURL) {
dispatch_async(dispatch_get_main_queue(), {
let player = AVPlayer(URL: appLocalUrl)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
view.presentViewController(playerViewController, animated: true) {
playerViewController.player!.play()
}
})
}
@Sazzad Hissain Khan solution in Swift 3:
From PHAsset:
func playVideo (view: UIViewController, videoAsset: PHAsset) {
guard (videoAsset.mediaType == .video) else {
print("Not a valid video media type")
return
}
PHCachingImageManager().requestAVAsset(forVideo: videoAsset, options: nil) { (asset, audioMix, args) in
let asset = asset as! AVURLAsset
DispatchQueue.main.async {
let player = AVPlayer(url: asset.url)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
view.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
}
}
From AppLocalUrl:
func playVideo (view: UIViewController, appLocalUrl: URL) {
DispatchQueue.main.async {
let player = AVPlayer(url: appLocalUrl)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
view.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
}